diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 6404cef2..6061aeec 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -17,6 +17,9 @@ Steps to reproduce the behavior. A clear and concise description of what you expected to happen. **Required data** + - XMRig version + - Either the exact link to a release you downloaded from https://github.com/xmrig/xmrig/releases + - Or the exact command lines that you used to build XMRig - Miner log as text or screenshot - Config file or command line (without wallets) - OS: [e.g. Windows] diff --git a/.gitignore b/.gitignore index 9263a0c7..3db117d4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ /build +scripts/build +scripts/deps /CMakeLists.txt.user /.idea /src/backend/opencl/cl/cn/cryptonight_gen.cl diff --git a/CHANGELOG.md b/CHANGELOG.md index e4f53c5a..f2e477dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,511 @@ +# v6.24.0 +- [#3671](https://github.com/xmrig/xmrig/pull/3671) Fixed detection of L2 cache size for some complex NUMA topologies. +- [#3674](https://github.com/xmrig/xmrig/pull/3674) Fixed ARMv7 build. +- [#3677](https://github.com/xmrig/xmrig/pull/3677) Fixed auto-config for AMD CPUs with less than 2 MB L3 cache per thread. +- [#3678](https://github.com/xmrig/xmrig/pull/3678) Improved IPv6 support: the new default settings use IPv6 equally with IPv4. + +# v6.23.0 +- [#3668](https://github.com/xmrig/xmrig/issues/3668) Added support for Windows ARM64. +- [#3665](https://github.com/xmrig/xmrig/pull/3665) Tweaked auto-config for AMD CPUs with < 2 MB L3 cache per thread. + +# v6.22.3 +- [#3605](https://github.com/xmrig/xmrig/pull/3605) CUDA backend: added missing RandomX dataset update. +- [#3646](https://github.com/xmrig/xmrig/pull/3646) Optimized auto-config for AMD CPUs with less than 2 MB L3 cache per thread. +- [#3652](https://github.com/xmrig/xmrig/pull/3652) Fixed possible crash when submitting RandomX benchmark. +- [#3662](https://github.com/xmrig/xmrig/pull/3662) Fixed OpenCL kernel compilation error on some platforms. + +# v6.22.2 +- [#3569](https://github.com/xmrig/xmrig/pull/3569) Fixed corrupted API output in some rare conditions. +- [#3571](https://github.com/xmrig/xmrig/pull/3571) Fixed number of threads on the new Intel Core Ultra CPUs. + +# v6.22.1 +- [#3531](https://github.com/xmrig/xmrig/pull/3531) Always reset nonce on RandomX dataset change. +- [#3534](https://github.com/xmrig/xmrig/pull/3534) Fixed threads auto-config on Zen5. +- [#3535](https://github.com/xmrig/xmrig/pull/3535) RandomX: tweaks for Zen5. +- [#3539](https://github.com/xmrig/xmrig/pull/3539) Added Zen5 to `randomx_boost.sh`. +- [#3540](https://github.com/xmrig/xmrig/pull/3540) Detect AMD engineering samples in `randomx_boost.sh`. + +# v6.22.0 +- [#2411](https://github.com/xmrig/xmrig/pull/2411) Added support for [Yada](https://yadacoin.io/) (`rx/yada` algorithm). +- [#3492](https://github.com/xmrig/xmrig/pull/3492) Fixed `--background` option on Unix systems. +- [#3518](https://github.com/xmrig/xmrig/pull/3518) Possible fix for corrupted API output in rare cases. +- [#3522](https://github.com/xmrig/xmrig/pull/3522) Removed `rx/keva` algorithm. +- [#3525](https://github.com/xmrig/xmrig/pull/3525) Added Zen5 detection. +- [#3528](https://github.com/xmrig/xmrig/pull/3528) Added `rx/yada` OpenCL support. + +# v6.21.3 +- [#3462](https://github.com/xmrig/xmrig/pull/3462) RandomX: correct memcpy size for JIT initialization. + +# v6.21.2 +- The dependencies of all prebuilt releases have been updated. Support for old Ubuntu releases has been dropped. +- [#2800](https://github.com/xmrig/xmrig/issues/2800) Fixed donation with GhostRider algorithm for builds without KawPow algorithm. +- [#3436](https://github.com/xmrig/xmrig/pull/3436) Fixed, the file log writer was not thread-safe. +- [#3450](https://github.com/xmrig/xmrig/pull/3450) Fixed RandomX crash when compiled with fortify_source. + +# v6.21.1 +- [#3391](https://github.com/xmrig/xmrig/pull/3391) Added support for townforge (monero fork using randomx). +- [#3399](https://github.com/xmrig/xmrig/pull/3399) Fixed Zephyr mining (OpenCL). +- [#3420](https://github.com/xmrig/xmrig/pull/3420) Fixed segfault in HTTP API rebind. + +# v6.21.0 +- [#3302](https://github.com/xmrig/xmrig/pull/3302) [#3312](https://github.com/xmrig/xmrig/pull/3312) Enabled keepalive for Windows (>= Vista). +- [#3320](https://github.com/xmrig/xmrig/pull/3320) Added "built for OS/architecture/bits" to "ABOUT". +- [#3339](https://github.com/xmrig/xmrig/pull/3339) Added SNI option for TLS connections. +- [#3342](https://github.com/xmrig/xmrig/pull/3342) Update `cn_main_loop.asm`. +- [#3346](https://github.com/xmrig/xmrig/pull/3346) ARM64 JIT: don't use `x18` register. +- [#3348](https://github.com/xmrig/xmrig/pull/3348) Update to latest `sse2neon.h`. +- [#3356](https://github.com/xmrig/xmrig/pull/3356) Updated pricing record size for **Zephyr** solo mining. +- [#3358](https://github.com/xmrig/xmrig/pull/3358) **Zephyr** solo mining: handle multiple outputs. + +# v6.20.0 +- Added new ARM CPU names. +- [#2394](https://github.com/xmrig/xmrig/pull/2394) Added new CMake options `ARM_V8` and `ARM_V7`. +- [#2830](https://github.com/xmrig/xmrig/pull/2830) Added API rebind polling. +- [#2927](https://github.com/xmrig/xmrig/pull/2927) Fixed compatibility with hwloc 1.11.x. +- [#3060](https://github.com/xmrig/xmrig/pull/3060) Added x86 to `README.md`. +- [#3236](https://github.com/xmrig/xmrig/pull/3236) Fixed: receive CUDA loader error on Linux too. +- [#3290](https://github.com/xmrig/xmrig/pull/3290) Added [Zephyr](https://www.zephyrprotocol.com/) coin support for solo mining. + +# v6.19.3 +- [#3245](https://github.com/xmrig/xmrig/issues/3245) Improved algorithm negotiation for donation rounds by sending extra information about current mining job. +- [#3254](https://github.com/xmrig/xmrig/pull/3254) Tweaked auto-tuning for Intel CPUs. +- [#3271](https://github.com/xmrig/xmrig/pull/3271) RandomX: optimized program generation. +- [#3273](https://github.com/xmrig/xmrig/pull/3273) RandomX: fixed undefined behavior. +- [#3275](https://github.com/xmrig/xmrig/pull/3275) RandomX: fixed `jccErratum` list. +- [#3280](https://github.com/xmrig/xmrig/pull/3280) Updated example scripts. + +# v6.19.2 +- [#3230](https://github.com/xmrig/xmrig/pull/3230) Fixed parsing of `TX_EXTRA_MERGE_MINING_TAG`. +- [#3232](https://github.com/xmrig/xmrig/pull/3232) Added new `X-Hash-Difficulty` HTTP header. +- [#3240](https://github.com/xmrig/xmrig/pull/3240) Improved .cmd files when run by shortcuts on another drive. +- [#3241](https://github.com/xmrig/xmrig/pull/3241) Added view tag calculation (fixes Wownero solo mining issue). + +# v6.19.1 +- Resolved deprecated methods warnings with OpenSSL 3.0. +- [#3213](https://github.com/xmrig/xmrig/pull/3213) Fixed build with 32-bit clang 15. +- [#3218](https://github.com/xmrig/xmrig/pull/3218) Fixed: `--randomx-wrmsr=-1` worked only on Intel. +- [#3228](https://github.com/xmrig/xmrig/pull/3228) Fixed build with gcc 13. + +# v6.19.0 +- [#3144](https://github.com/xmrig/xmrig/pull/3144) Update to latest `sse2neon.h`. +- [#3161](https://github.com/xmrig/xmrig/pull/3161) MSVC build: enabled parallel compilation. +- [#3163](https://github.com/xmrig/xmrig/pull/3163) Improved Zen 3 MSR mod. +- [#3176](https://github.com/xmrig/xmrig/pull/3176) Update cmake required version to 3.1. +- [#3182](https://github.com/xmrig/xmrig/pull/3182) DragonflyBSD compilation fixes. +- [#3196](https://github.com/xmrig/xmrig/pull/3196) Show IP address for failed connections. +- [#3185](https://github.com/xmrig/xmrig/issues/3185) Fixed macOS DMI reader. +- [#3198](https://github.com/xmrig/xmrig/pull/3198) Fixed broken RandomX light mode mining. +- [#3202](https://github.com/xmrig/xmrig/pull/3202) Solo mining: added job timeout (default is 15 seconds). + +# v6.18.1 +- [#3129](https://github.com/xmrig/xmrig/pull/3129) Fix: protectRX flushed CPU cache only on MacOS/iOS. +- [#3126](https://github.com/xmrig/xmrig/pull/3126) Don't reset when pool sends the same job blob. +- [#3120](https://github.com/xmrig/xmrig/pull/3120) RandomX: optimized `CFROUND` elimination. +- [#3109](https://github.com/xmrig/xmrig/pull/3109) RandomX: added Blake2 AVX2 version. +- [#3082](https://github.com/xmrig/xmrig/pull/3082) Fixed GCC 12 warnings. +- [#3075](https://github.com/xmrig/xmrig/pull/3075) Recognize `armv7ve` as valid ARMv7 target. +- [#3132](https://github.com/xmrig/xmrig/pull/3132) RandomX: added MSR mod for Zen 4. +- [#3134](https://github.com/xmrig/xmrig/pull/3134) Added Zen4 to `randomx_boost.sh`. + +# v6.18.0 +- [#3067](https://github.com/xmrig/xmrig/pull/3067) Monero v15 network upgrade support and more house keeping. + - Removed deprecated AstroBWTv1 and v2. + - Fixed debug GhostRider build. + - Monero v15 network upgrade support. + - Fixed ZMQ debug log. + - Improved daemon ZMQ mining stability. +- [#3054](https://github.com/xmrig/xmrig/pull/3054) Fixes for 32-bit ARM. +- [#3042](https://github.com/xmrig/xmrig/pull/3042) Fixed being unable to resume from `pause-on-battery`. +- [#3031](https://github.com/xmrig/xmrig/pull/3031) Fixed `--cpu-priority` not working sometimes. +- [#3020](https://github.com/xmrig/xmrig/pull/3020) Removed old AstroBWT algorithm. + +# v6.17.0 +- [#2954](https://github.com/xmrig/xmrig/pull/2954) **Dero HE fork support (`astrobwt/v2` algorithm).** + - [#2961](https://github.com/xmrig/xmrig/pull/2961) Dero HE (`astrobwt/v2`) CUDA config generator. + - [#2969](https://github.com/xmrig/xmrig/pull/2969) Dero HE (`astrobwt/v2`) OpenCL support. +- Fixed displayed DMI memory information for empty slots. +- [#2932](https://github.com/xmrig/xmrig/pull/2932) Fixed GhostRider with hwloc disabled. + +# v6.16.4 +- [#2904](https://github.com/xmrig/xmrig/pull/2904) Fixed unaligned memory accesses. +- [#2908](https://github.com/xmrig/xmrig/pull/2908) Added MSVC/2022 to `version.h`. +- [#2910](https://github.com/xmrig/xmrig/issues/2910) Fixed donation for GhostRider/RTM. + +# v6.16.3 +- [#2778](https://github.com/xmrig/xmrig/pull/2778) Fixed `READY threads X/X` display after algorithm switching. +- [#2782](https://github.com/xmrig/xmrig/pull/2782) Updated GhostRider documentation. +- [#2815](https://github.com/xmrig/xmrig/pull/2815) Fixed `cn-heavy` in 32-bit builds. +- [#2827](https://github.com/xmrig/xmrig/pull/2827) GhostRider: set correct priority for helper threads. +- [#2837](https://github.com/xmrig/xmrig/pull/2837) RandomX: don't restart mining threads when the seed changes. +- [#2848](https://github.com/xmrig/xmrig/pull/2848) GhostRider: added support for `client.reconnect` method. +- [#2856](https://github.com/xmrig/xmrig/pull/2856) Fix for short responses from some Raptoreum pools. +- [#2873](https://github.com/xmrig/xmrig/pull/2873) Fixed GhostRider benchmark on single-core systems. +- [#2882](https://github.com/xmrig/xmrig/pull/2882) Fixed ARMv7 compilation. +- [#2893](https://github.com/xmrig/xmrig/pull/2893) KawPow OpenCL: use separate UV loop for building programs. + +# v6.16.2 +- [#2751](https://github.com/xmrig/xmrig/pull/2751) Fixed crash on CPUs supporting VAES and running GCC-compiled xmrig. +- [#2761](https://github.com/xmrig/xmrig/pull/2761) Fixed broken auto-tuning in GCC Windows build. +- [#2771](https://github.com/xmrig/xmrig/issues/2771) Fixed environment variables support for GhostRider and KawPow. +- [#2769](https://github.com/xmrig/xmrig/pull/2769) Performance fixes: + - Fixed several performance bottlenecks introduced in v6.16.1. + - Fixed overall GCC-compiled build performance, it's the same speed as MSVC build now. + - **Linux builds are up to 10% faster now compared to v6.16.0 GCC build.** + - **Windows builds are up to 5% faster now compared to v6.16.0 MSVC build.** + +# v6.16.1 +- [#2729](https://github.com/xmrig/xmrig/pull/2729) GhostRider fixes: + - Added average hashrate display. + - Fixed the number of threads shown at startup. + - Fixed `--threads` or `-t` command line option (but `--cpu-max-threads-hint` is recommended to use). +- [#2738](https://github.com/xmrig/xmrig/pull/2738) GhostRider fixes: + - Fixed "difficulty is not a number" error when diff is high on some pools. + - Fixed GhostRider compilation when `WITH_KAWPOW=OFF`. +- [#2740](https://github.com/xmrig/xmrig/pull/2740) Added VAES support for Cryptonight variants **+4% speedup on Zen3**. + - VAES instructions are available on Intel Ice Lake/AMD Zen3 and newer CPUs. + - +4% speedup on Ryzen 5 5600X. + +# v6.16.0 +- [#2712](https://github.com/xmrig/xmrig/pull/2712) **GhostRider algorithm (Raptoreum) support**: read the [RELEASE NOTES](src/crypto/ghostrider/README.md) for quick start guide and performance comparisons. +- [#2682](https://github.com/xmrig/xmrig/pull/2682) Fixed: use cn-heavy optimization only for Vermeer CPUs. +- [#2684](https://github.com/xmrig/xmrig/pull/2684) MSR mod: fix for error 183. + +# v6.15.3 +- [#2614](https://github.com/xmrig/xmrig/pull/2614) OpenCL fixes for non-AMD platforms. +- [#2623](https://github.com/xmrig/xmrig/pull/2623) Fixed compiling without kawpow. +- [#2636](https://github.com/xmrig/xmrig/pull/2636) [#2639](https://github.com/xmrig/xmrig/pull/2639) AstroBWT speedup (up to +35%). +- [#2646](https://github.com/xmrig/xmrig/pull/2646) Fixed MSVC compilation error. + +# v6.15.2 +- [#2606](https://github.com/xmrig/xmrig/pull/2606) Fixed: AstroBWT auto-config ignored `max-threads-hint`. +- Fixed possible crash on Windows (regression in v6.15.1). + +# v6.15.1 +- [#2586](https://github.com/xmrig/xmrig/pull/2586) Fixed Windows 7 compatibility. +- [#2594](https://github.com/xmrig/xmrig/pull/2594) Added Windows taskbar icon colors. + +# v6.15.0 +- [#2548](https://github.com/xmrig/xmrig/pull/2548) Added automatic coin detection for daemon mining. +- [#2563](https://github.com/xmrig/xmrig/pull/2563) Added new algorithm RandomX Graft (`rx/graft`). +- [#2565](https://github.com/xmrig/xmrig/pull/2565) AstroBWT: added AVX2 Salsa20 implementation. +- Added support for new CUDA plugin API (previous API still supported). + +# v6.14.1 +- [#2532](https://github.com/xmrig/xmrig/pull/2532) Refactoring: stable (persistent) algorithms IDs. +- [#2537](https://github.com/xmrig/xmrig/pull/2537) Fixed Termux build. + +# v6.14.0 +- [#2484](https://github.com/xmrig/xmrig/pull/2484) Added ZeroMQ support for solo mining. +- [#2476](https://github.com/xmrig/xmrig/issues/2476) Fixed crash in DMI memory reader. +- [#2492](https://github.com/xmrig/xmrig/issues/2492) Added missing `--huge-pages-jit` command line option. +- [#2512](https://github.com/xmrig/xmrig/pull/2512) Added show the number of transactions in pool job. + +# v6.13.1 +- [#2468](https://github.com/xmrig/xmrig/pull/2468) Fixed regression in previous version: don't send miner signature during regular mining. + +# v6.13.0 +- [#2445](https://github.com/xmrig/xmrig/pull/2445) Added support for solo mining with miner signatures for the upcoming Wownero fork. + +# v6.12.2 +- [#2280](https://github.com/xmrig/xmrig/issues/2280) GPU backends are now disabled in benchmark mode. +- [#2322](https://github.com/xmrig/xmrig/pull/2322) Improved MSR compatibility with recent Linux kernels and updated `randomx_boost.sh`. +- [#2340](https://github.com/xmrig/xmrig/pull/2340) Fixed AES detection on FreeBSD on ARM. +- [#2341](https://github.com/xmrig/xmrig/pull/2341) `sse2neon` updated to the latest version. +- [#2351](https://github.com/xmrig/xmrig/issues/2351) Fixed help output for `--cpu-priority` and `--cpu-affinity` option. +- [#2375](https://github.com/xmrig/xmrig/pull/2375) Fixed macOS CUDA backend default loader name. +- [#2378](https://github.com/xmrig/xmrig/pull/2378) Fixed broken light mode mining on x86. +- [#2379](https://github.com/xmrig/xmrig/pull/2379) Fixed CL code for KawPow where it assumes everything is AMD. +- [#2386](https://github.com/xmrig/xmrig/pull/2386) RandomX: enabled `IMUL_RCP` optimization for light mode mining. +- [#2393](https://github.com/xmrig/xmrig/pull/2393) RandomX: added BMI2 version for scratchpad prefetch. +- [#2395](https://github.com/xmrig/xmrig/pull/2395) RandomX: rewrote dataset read code. +- [#2398](https://github.com/xmrig/xmrig/pull/2398) RandomX: optimized ARMv8 dataset read. +- Added `argon2/ninja` alias for `argon2/wrkz` algorithm. + +# v6.12.1 +- [#2296](https://github.com/xmrig/xmrig/pull/2296) Fixed Zen3 assembly code for `cn/upx2` algorithm. + +# v6.12.0 +- [#2276](https://github.com/xmrig/xmrig/pull/2276) Added support for Uplexa (`cn/upx2` algorithm). +- [#2261](https://github.com/xmrig/xmrig/pull/2261) Show total hashrate if compiled without OpenCL. +- [#2289](https://github.com/xmrig/xmrig/pull/2289) RandomX: optimized `IMUL_RCP` instruction. +- Added support for `--user` command line option for online benchmark. + +# v6.11.2 +- [#2207](https://github.com/xmrig/xmrig/issues/2207) Fixed regression in HTTP parser and llhttp updated to v5.1.0. + +# v6.11.1 +- [#2239](https://github.com/xmrig/xmrig/pull/2239) Fixed broken `coin` setting functionality. + +# v6.11.0 +- [#2196](https://github.com/xmrig/xmrig/pull/2196) Improved DNS subsystem and added new DNS specific options. +- [#2172](https://github.com/xmrig/xmrig/pull/2172) Fixed build on Alpine 3.13. +- [#2177](https://github.com/xmrig/xmrig/pull/2177) Fixed ARM specific compilation error with GCC 10.2. +- [#2214](https://github.com/xmrig/xmrig/pull/2214) [#2216](https://github.com/xmrig/xmrig/pull/2216) [#2235](https://github.com/xmrig/xmrig/pull/2235) Optimized `cn-heavy` algorithm. +- [#2217](https://github.com/xmrig/xmrig/pull/2217) Fixed mining job creation sequence. +- [#2225](https://github.com/xmrig/xmrig/pull/2225) Fixed build without OpenCL support on some systems. +- [#2229](https://github.com/xmrig/xmrig/pull/2229) Don't use RandomX JIT if `WITH_ASM=OFF`. +- [#2228](https://github.com/xmrig/xmrig/pull/2228) Removed useless code for cryptonight algorithms. +- [#2234](https://github.com/xmrig/xmrig/pull/2234) Fixed build error on gcc 4.8. + +# v6.10.0 +- [#2122](https://github.com/xmrig/xmrig/pull/2122) Fixed pause logic when both pause on battery and user activity are enabled. +- [#2123](https://github.com/xmrig/xmrig/issues/2123) Fixed compatibility with gcc 4.8. +- [#2147](https://github.com/xmrig/xmrig/pull/2147) Fixed many `new job` messages when solo mining. +- [#2150](https://github.com/xmrig/xmrig/pull/2150) Updated `sse2neon.h` to the latest master, fixes build on ARMv7. +- [#2157](https://github.com/xmrig/xmrig/pull/2157) Fixed crash in `cn-heavy` on Zen3 with manual thread count. +- Fixed possible out of order write to log file. +- [http-parser](https://github.com/nodejs/http-parser) replaced to [llhttp](https://github.com/nodejs/llhttp). +- For official builds: libuv, hwloc and OpenSSL updated to latest versions. + +# v6.9.0 +- [#2104](https://github.com/xmrig/xmrig/pull/2104) Added [pause-on-active](https://xmrig.com/docs/miner/config/misc#pause-on-active) config option and `--pause-on-active=N` command line option. +- [#2112](https://github.com/xmrig/xmrig/pull/2112) Added support for [Tari merge mining](https://github.com/tari-project/tari/blob/development/README.md#tari-merge-mining). +- [#2117](https://github.com/xmrig/xmrig/pull/2117) Fixed crash when GPU mining `cn-heavy` on Zen3 system. + +# v6.8.2 +- [#2080](https://github.com/xmrig/xmrig/pull/2080) Fixed compile error in Termux. +- [#2089](https://github.com/xmrig/xmrig/pull/2089) Optimized CryptoNight-Heavy for Zen3, 7-8% speedup. + +# v6.8.1 +- [#2064](https://github.com/xmrig/xmrig/pull/2064) Added documentation for config.json CPU options. +- [#2066](https://github.com/xmrig/xmrig/issues/2066) Fixed AMD GPUs health data readings on Linux. +- [#2067](https://github.com/xmrig/xmrig/pull/2067) Fixed compilation error when RandomX and Argon2 are disabled. +- [#2076](https://github.com/xmrig/xmrig/pull/2076) Added support for flexible huge page sizes on Linux. +- [#2077](https://github.com/xmrig/xmrig/pull/2077) Fixed `illegal instruction` crash on ARM. + +# v6.8.0 +- [#2052](https://github.com/xmrig/xmrig/pull/2052) Added DMI/SMBIOS reader. + - Added information about memory modules on the miner startup and for online benchmark. + - Added new HTTP API endpoint: `GET /2/dmi`. + - Added new command line option `--no-dmi` or config option `"dmi"`. + - Added new CMake option `-DWITH_DMI=OFF`. +- [#2057](https://github.com/xmrig/xmrig/pull/2057) Improved MSR subsystem code quality. +- [#2058](https://github.com/xmrig/xmrig/pull/2058) RandomX JIT x86: removed unnecessary instructions. + +# v6.7.2 +- [#2039](https://github.com/xmrig/xmrig/pull/2039) Fixed solo mining. + +# v6.7.1 +- [#1995](https://github.com/xmrig/xmrig/issues/1995) Fixed log initialization. +- [#1998](https://github.com/xmrig/xmrig/pull/1998) Added hashrate in the benchmark finished message. +- [#2009](https://github.com/xmrig/xmrig/pull/2009) AstroBWT OpenCL fixes. +- [#2028](https://github.com/xmrig/xmrig/pull/2028) RandomX x86 JIT: removed redundant `CFROUND`. + +# v6.7.0 +- **[#1991](https://github.com/xmrig/xmrig/issues/1991) Added Apple M1 processor support.** +- **[#1986](https://github.com/xmrig/xmrig/pull/1986) Up to 20-30% faster RandomX dataset initialization with AVX2 on some CPUs.** +- [#1964](https://github.com/xmrig/xmrig/pull/1964) Cleanup and refactoring. +- [#1966](https://github.com/xmrig/xmrig/pull/1966) Removed libcpuid support. +- [#1968](https://github.com/xmrig/xmrig/pull/1968) Added virtual machine detection. +- [#1969](https://github.com/xmrig/xmrig/pull/1969) [#1970](https://github.com/xmrig/xmrig/pull/1970) Fixed errors found by static analysis. +- [#1977](https://github.com/xmrig/xmrig/pull/1977) Fixed: secure JIT and huge pages are incompatible on Windows. +- [#1979](https://github.com/xmrig/xmrig/pull/1979) Term `x64` replaced to `64-bit`. +- [#1980](https://github.com/xmrig/xmrig/pull/1980) Fixed build on gcc 11. +- [#1989](https://github.com/xmrig/xmrig/pull/1989) Fixed broken Dero solo mining. + +# v6.6.2 +- [#1958](https://github.com/xmrig/xmrig/pull/1958) Added example mining scripts to help new miners. +- [#1959](https://github.com/xmrig/xmrig/pull/1959) Optimized JIT compiler. +- [#1960](https://github.com/xmrig/xmrig/pull/1960) Fixed RandomX init when switching to other algo and back. + +# v6.6.1 +- Fixed, benchmark validation on NUMA hardware produced incorrect results in some conditions. + +# v6.6.0 +- Online benchmark protocol upgraded to v2, validation not compatible with previous versions. + - Single thread benchmark now is cheat-resistant, not possible speedup it with multiple threads. + - RandomX dataset is now always initialized with static seed, to prevent time cheat by report slow dataset initialization. + - Zero delay online submission, to make time validation much more precise and strict. + - DNS cache for online benchmark to prevent unexpected delays. + +# v6.5.3 +- [#1946](https://github.com/xmrig/xmrig/pull/1946) Fixed MSR mod names in JSON API (v6.5.2 affected). + +# v6.5.2 +- [#1935](https://github.com/xmrig/xmrig/pull/1935) Separate MSR mod for Zen/Zen2 and Zen3. +- [#1937](https://github.com/xmrig/xmrig/issues/1937) Print path to existing WinRing0 service without verbose option. +- [#1939](https://github.com/xmrig/xmrig/pull/1939) Fixed build with gcc 4.8. +- [#1941](https://github.com/xmrig/xmrig/pull/1941) Added CPUID info to JSON report. +- [#1941](https://github.com/xmrig/xmrig/pull/1942) Fixed alignment modification in memory pool. +- [#1944](https://github.com/xmrig/xmrig/pull/1944) Updated `randomx_boost.sh` with new MSR mod. +- Added `250K` and `500K` offline benchmarks. + +# v6.5.1 +- [#1932](https://github.com/xmrig/xmrig/pull/1932) New MSR mod for Ryzen, up to +3.5% on Zen2 and +1-2% on Zen3. +- [#1918](https://github.com/xmrig/xmrig/issues/1918) Fixed 1GB huge pages support on ARMv8. +- [#1926](https://github.com/xmrig/xmrig/pull/1926) Fixed compilation on ARMv8 with GCC 9.3.0. +- [#1929](https://github.com/xmrig/xmrig/issues/1929) Fixed build without HTTP. + +# v6.5.0 +- **Added [online benchmark](https://xmrig.com/benchmark) mode for sharing results.** + - Added new command line options: `--submit`, ` --verify=ID`, ` --seed=SEED`, `--hash=HASH`. +- [#1912](https://github.com/xmrig/xmrig/pull/1912) Fixed MSR kernel module warning with new Linux kernels. +- [#1925](https://github.com/xmrig/xmrig/pull/1925) Add checking for config files in user home directory. +- Added vendor to ARM CPUs name and added `"arch"` field to API. +- Removed legacy CUDA plugin API. + +# v6.4.0 +- [#1862](https://github.com/xmrig/xmrig/pull/1862) **RandomX: removed `rx/loki` algorithm.** +- [#1890](https://github.com/xmrig/xmrig/pull/1890) **Added `argon2/chukwav2` algorithm.** +- [#1895](https://github.com/xmrig/xmrig/pull/1895) [#1897](https://github.com/xmrig/xmrig/pull/1897) **Added [benchmark and stress test](https://github.com/xmrig/xmrig/blob/dev/doc/BENCHMARK.md).** +- [#1864](https://github.com/xmrig/xmrig/pull/1864) RandomX: improved software AES performance. +- [#1870](https://github.com/xmrig/xmrig/pull/1870) RandomX: fixed unexpected resume due to disconnect during dataset init. +- [#1872](https://github.com/xmrig/xmrig/pull/1872) RandomX: fixed `randomx_create_vm` call. +- [#1875](https://github.com/xmrig/xmrig/pull/1875) RandomX: fixed crash on x86. +- [#1876](https://github.com/xmrig/xmrig/pull/1876) RandomX: added `huge-pages-jit` config parameter. +- [#1881](https://github.com/xmrig/xmrig/pull/1881) Fixed possible race condition in hashrate counting code. +- [#1882](https://github.com/xmrig/xmrig/pull/1882) [#1886](https://github.com/xmrig/xmrig/pull/1886) [#1887](https://github.com/xmrig/xmrig/pull/1887) [#1893](https://github.com/xmrig/xmrig/pull/1893) General code improvements. +- [#1885](https://github.com/xmrig/xmrig/pull/1885) Added more precise hashrate calculation. +- [#1889](https://github.com/xmrig/xmrig/pull/1889) Fixed libuv performance issue on Linux. + +# v6.3.5 +- [#1845](https://github.com/xmrig/xmrig/pull/1845) [#1861](https://github.com/xmrig/xmrig/pull/1861) Fixed ARM build and added CMake option `WITH_SSE4_1`. +- [#1846](https://github.com/xmrig/xmrig/pull/1846) KawPow: fixed OpenCL memory leak. +- [#1849](https://github.com/xmrig/xmrig/pull/1849) [#1859](https://github.com/xmrig/xmrig/pull/1859) RandomX: optimized soft AES code. +- [#1850](https://github.com/xmrig/xmrig/pull/1850) [#1852](https://github.com/xmrig/xmrig/pull/1852) General code improvements. +- [#1853](https://github.com/xmrig/xmrig/issues/1853) [#1856](https://github.com/xmrig/xmrig/pull/1856) [#1857](https://github.com/xmrig/xmrig/pull/1857) Fixed crash on old CPUs. + +# v6.3.4 +- [#1823](https://github.com/xmrig/xmrig/pull/1823) RandomX: added new option `scratchpad_prefetch_mode`. +- [#1827](https://github.com/xmrig/xmrig/pull/1827) [#1831](https://github.com/xmrig/xmrig/pull/1831) Improved nonce iteration performance. +- [#1828](https://github.com/xmrig/xmrig/pull/1828) RandomX: added SSE4.1-optimized Blake2b. +- [#1830](https://github.com/xmrig/xmrig/pull/1830) RandomX: added performance profiler (for developers). +- [#1835](https://github.com/xmrig/xmrig/pull/1835) RandomX: returned old soft AES implementation and added auto-select between the two. +- [#1840](https://github.com/xmrig/xmrig/pull/1840) RandomX: moved more stuff to compile time, small x86 JIT compiler speedup. +- [#1841](https://github.com/xmrig/xmrig/pull/1841) Fixed Cryptonight OpenCL for AMD 20.7.2 drivers. +- [#1842](https://github.com/xmrig/xmrig/pull/1842) RandomX: AES improvements, a bit faster hardware AES code when compiled with MSVC. +- [#1843](https://github.com/xmrig/xmrig/pull/1843) RandomX: improved performance of GCC compiled binaries. + +# v6.3.3 +- [#1817](https://github.com/xmrig/xmrig/pull/1817) Fixed self-select login sequence. +- Added brand new [build from source](https://xmrig.com/docs/miner/build) documentation. +- New binary downloads for macOS (`macos-x64`), FreeBSD (`freebsd-static-x64`), Linux (`linux-static-x64`), Ubuntu 18.04 (`bionic-x64`), Ubuntu 20.04 (`focal-x64`). +- Generic Linux download `xenial-x64` renamed to `linux-x64`. +- Builds without SSL/TLS support are no longer provided. +- Improved CUDA loader error reporting and fixed plugin load on Linux. +- Fixed build warnings with Clang compiler. +- Fixed colors on macOS. + +# v6.3.2 +- [#1794](https://github.com/xmrig/xmrig/pull/1794) More robust 1 GB pages handling. + - Don't allocate 1 GB per thread if 1 GB is the default huge page size. + - Try to allocate scratchpad from dataset's 1 GB huge pages, if normal huge pages are not available. + - Correctly initialize RandomX cache if 1 GB pages fail to allocate on a first NUMA node. +- [#1806](https://github.com/xmrig/xmrig/pull/1806) Fixed macOS battery detection. +- [#1809](https://github.com/xmrig/xmrig/issues/1809) Improved auto configuration on ARM CPUs. + - Added retrieving ARM CPU names, based on lscpu code and database. + +# v6.3.1 +- [#1786](https://github.com/xmrig/xmrig/pull/1786) Added `pause-on-battery` option, supported on Windows and Linux. +- Added command line options `--randomx-cache-qos` and `--argon2-impl`. + +# v6.3.0 +- [#1771](https://github.com/xmrig/xmrig/pull/1771) Adopted new SSE2NEON and reduced ARM-specific changes. +- [#1774](https://github.com/xmrig/xmrig/pull/1774) RandomX: Added new option `cache_qos` in `randomx` object for cache QoS support. +- [#1777](https://github.com/xmrig/xmrig/pull/1777) Added support for upcoming Haven offshore fork. + - [#1780](https://github.com/xmrig/xmrig/pull/1780) CryptoNight OpenCL: fix for long input data. + +# v6.2.3 +- [#1745](https://github.com/xmrig/xmrig/pull/1745) AstroBWT: fixed OpenCL compilation on some systems. +- [#1749](https://github.com/xmrig/xmrig/pull/1749) KawPow: optimized CPU share verification. +- [#1752](https://github.com/xmrig/xmrig/pull/1752) RandomX: added error message when MSR mod fails. +- [#1754](https://github.com/xmrig/xmrig/issues/1754) Fixed GPU health readings for pre Vega GPUs on Linux. +- [#1756](https://github.com/xmrig/xmrig/issues/1756) Added results and connection reports. +- [#1759](https://github.com/xmrig/xmrig/pull/1759) KawPow: fixed DAG initialization on slower AMD GPUs. +- [#1763](https://github.com/xmrig/xmrig/pull/1763) KawPow: fixed rare duplicate share errors. +- [#1766](https://github.com/xmrig/xmrig/pull/1766) RandomX: small speedup on Ryzen CPUs. + +# v6.2.2 +- [#1742](https://github.com/xmrig/xmrig/issues/1742) Fixed crash when use HTTP API. + +# v6.2.1 +- [#1726](https://github.com/xmrig/xmrig/issues/1726) Fixed detection of AVX2/AVX512. +- [#1728](https://github.com/xmrig/xmrig/issues/1728) Fixed, 32 bit Windows builds was crash on start. +- [#1729](https://github.com/xmrig/xmrig/pull/1729) Fixed KawPow crash on old CPUs. +- [#1730](https://github.com/xmrig/xmrig/pull/1730) Improved displaying information for compute errors on GPUs. +- [#1732](https://github.com/xmrig/xmrig/pull/1732) Fixed NiceHash disconnects for KawPow. +- Fixed AMD GPU health (temperatures/power/clocks/fans) readings on Linux. + +# v6.2.0-beta +- [#1717](https://github.com/xmrig/xmrig/pull/1717) Added new algorithm `cn/ccx` for Conceal. +- [#1718](https://github.com/xmrig/xmrig/pull/1718) Fixed, linker on Linux was marking entire executable as having an executable stack. +- [#1720](https://github.com/xmrig/xmrig/pull/1720) Fixed broken CryptoNight algorithms family with gcc 10.1. + +# v6.0.1-beta +- [#1708](https://github.com/xmrig/xmrig/issues/1708) Added `title` option. +- [#1711](https://github.com/xmrig/xmrig/pull/1711) [cuda] Print errors from KawPow DAG initialization. +- [#1713](https://github.com/xmrig/xmrig/pull/1713) [cuda] Reduced memory usage for KawPow, minimum CUDA plugin version now is 6.1.0. + +# v6.0.0-beta +- [#1694](https://github.com/xmrig/xmrig/pull/1694) Added support for KawPow algorithm (Ravencoin) on AMD/NVIDIA. +- Removed previously deprecated `cn/gpu` algorithm. +- Default donation level reduced to 1% but you still can increase it if you like. + +# v5.11.3 +- [#1718](https://github.com/xmrig/xmrig/pull/1718) Fixed, linker on Linux was marking entire executable as having an executable stack. +- [#1720](https://github.com/xmrig/xmrig/pull/1720) Fixed broken CryptoNight algorithms family with gcc 10.1. + +# v5.11.2 +- [#1664](https://github.com/xmrig/xmrig/pull/1664) Improved JSON config error reporting. +- [#1668](https://github.com/xmrig/xmrig/pull/1668) Optimized RandomX dataset initialization. +- [#1675](https://github.com/xmrig/xmrig/pull/1675) Fixed cross-compiling on Linux. +- Fixed memory leak in HTTP client. +- Build [dependencies](https://github.com/xmrig/xmrig-deps/releases/tag/v4.1) updated to recent versions. +- Compiler for Windows gcc builds updated to v10.1. + +# v5.11.1 +- [#1652](https://github.com/xmrig/xmrig/pull/1652) Up to 1% RandomX perfomance improvement on recent AMD CPUs. +- [#1306](https://github.com/xmrig/xmrig/issues/1306) Fixed possible double connection to a pool. +- [#1654](https://github.com/xmrig/xmrig/issues/1654) Fixed build with LibreSSL. + +# v5.11.0 +- **[#1632](https://github.com/xmrig/xmrig/pull/1632) Added AstroBWT CUDA support ([CUDA plugin](https://github.com/xmrig/xmrig-cuda) v3.0.0 or newer required).** +- [#1605](https://github.com/xmrig/xmrig/pull/1605) Fixed AstroBWT OpenCL for NVIDIA GPUs. +- [#1635](https://github.com/xmrig/xmrig/pull/1635) Added pooled memory allocation of RandomX VMs (+0.5% speedup on Zen2). +- [#1641](https://github.com/xmrig/xmrig/pull/1641) RandomX JIT refactoring, smaller memory footprint and a bit faster overall. +- [#1643](https://github.com/xmrig/xmrig/issues/1643) Fixed build on CentOS 7. + +# v5.10.0 +- [#1602](https://github.com/xmrig/xmrig/pull/1602) Added AMD GPUs support for AstroBWT algorithm. +- [#1590](https://github.com/xmrig/xmrig/pull/1590) MSR mod automatically deactivated after switching from RandomX algorithms. +- [#1592](https://github.com/xmrig/xmrig/pull/1592) Added AVX2 optimized code for AstroBWT algorithm. + - Added new config option `astrobwt-avx2` in `cpu` object and command line option `--astrobwt-avx2`. +- [#1596](https://github.com/xmrig/xmrig/issues/1596) Major TLS (Transport Layer Security) subsystem update. + - Added new TLS options, please check [xmrig-proxy documentation](https://xmrig.com/docs/proxy/tls) for details. +- `cn/gpu` algorithm now disabled by default and will be removed in next major (v6.x.x) release, no ETA for it right now. +- Added command line option `--data-dir`. + +# v5.9.0 +- [#1578](https://github.com/xmrig/xmrig/pull/1578) Added new RandomKEVA algorithm for upcoming Kevacoin fork, as `"algo": "rx/keva"` or `"coin": "keva"`. +- [#1584](https://github.com/xmrig/xmrig/pull/1584) Fixed invalid AstroBWT hashes after algorithm switching. +- [#1585](https://github.com/xmrig/xmrig/issues/1585) Fixed build without HTTP support. +- Added command line option `--astrobwt-max-size`. + +# v5.8.2 +- [#1580](https://github.com/xmrig/xmrig/pull/1580) AstroBWT algorithm 20-50% speedup. + - Added new option `astrobwt-max-size`. +- [#1581](https://github.com/xmrig/xmrig/issues/1581) Fixed macOS build. + +# v5.8.1 +- [#1575](https://github.com/xmrig/xmrig/pull/1575) Fixed new block detection for DERO solo mining. + +# v5.8.0 +- [#1573](https://github.com/xmrig/xmrig/pull/1573) Added new AstroBWT algorithm for upcoming DERO fork, as `"algo": "astrobwt"` or `"coin": "dero"`. + +# v5.7.0 +- **Added SOCKS5 proxies support for Tor https://xmrig.com/docs/miner/tor.** +- [#377](https://github.com/xmrig/xmrig-proxy/issues/377) Fixed duplicate jobs in daemon (solo) mining client. +- [#1560](https://github.com/xmrig/xmrig/pull/1560) RandomX 0.3-0.4% speedup depending on CPU. +- Fixed possible crashes in HTTP client. + +# v5.6.0 +- [#1536](https://github.com/xmrig/xmrig/pull/1536) Added workaround for new AMD GPU drivers. +- [#1546](https://github.com/xmrig/xmrig/pull/1546) Fixed generic OpenCL code for AMD Navi GPUs. +- [#1551](https://github.com/xmrig/xmrig/pull/1551) Added RandomX JIT for AMD Navi GPUs. +- Added health information for AMD GPUs (clocks/power/fan/temperature) via ADL (Windows) and sysfs (Linux). +- Fixed possible nicehash nonce overflow in some conditions. +- Fixed wrong OpenCL platform on macOS, option `platform` now ignored on this OS. + # v5.5.3 - [#1529](https://github.com/xmrig/xmrig/pull/1529) Fixed crash on Bulldozer CPUs. diff --git a/CMakeLists.txt b/CMakeLists.txt index b6a9288c..31392322 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,14 +1,15 @@ -cmake_minimum_required(VERSION 2.8) +cmake_minimum_required(VERSION 3.10) project(xmrig) -option(WITH_LIBCPUID "Enable libcpuid support" ON) option(WITH_HWLOC "Enable hwloc support" ON) option(WITH_CN_LITE "Enable CryptoNight-Lite algorithms family" ON) option(WITH_CN_HEAVY "Enable CryptoNight-Heavy algorithms family" ON) option(WITH_CN_PICO "Enable CryptoNight-Pico algorithm" ON) -option(WITH_CN_GPU "Enable CryptoNight-GPU algorithm" ON) +option(WITH_CN_FEMTO "Enable CryptoNight-UPX2 algorithm" ON) option(WITH_RANDOMX "Enable RandomX algorithms family" ON) option(WITH_ARGON2 "Enable Argon2 algorithms family" ON) +option(WITH_KAWPOW "Enable KawPow algorithms family" ON) +option(WITH_GHOSTRIDER "Enable GhostRider algorithm" ON) option(WITH_HTTP "Enable HTTP protocol support (client/server)" ON) option(WITH_DEBUG_LOG "Enable debug log output" OFF) option(WITH_TLS "Enable OpenSSL support" ON) @@ -17,13 +18,24 @@ option(WITH_MSR "Enable MSR mod & 1st-gen Ryzen fix" ON) option(WITH_ENV_VARS "Enable environment variables support in config file" ON) option(WITH_EMBEDDED_CONFIG "Enable internal embedded JSON config" OFF) option(WITH_OPENCL "Enable OpenCL backend" ON) +set(WITH_OPENCL_VERSION 200 CACHE STRING "Target OpenCL version") +set_property(CACHE WITH_OPENCL_VERSION PROPERTY STRINGS 120 200 210 220) option(WITH_CUDA "Enable CUDA backend" ON) option(WITH_NVML "Enable NVML (NVIDIA Management Library) support (only if CUDA backend enabled)" ON) +option(WITH_ADL "Enable ADL (AMD Display Library) or sysfs support (only if OpenCL backend enabled)" ON) option(WITH_STRICT_CACHE "Enable strict checks for OpenCL cache" ON) option(WITH_INTERLEAVE_DEBUG_LOG "Enable debug log for threads interleave" OFF) +option(WITH_PROFILING "Enable profiling for developers" OFF) +option(WITH_SSE4_1 "Enable SSE 4.1 for Blake2" ON) +option(WITH_AVX2 "Enable AVX2 for Blake2" ON) +option(WITH_VAES "Enable VAES instructions for Cryptonight" ON) +option(WITH_BENCHMARK "Enable builtin RandomX benchmark and stress test" ON) +option(WITH_SECURE_JIT "Enable secure access to JIT memory" OFF) +option(WITH_DMI "Enable DMI/SMBIOS reader" ON) option(BUILD_STATIC "Build static binary" OFF) -option(ARM_TARGET "Force use specific ARM target 8 or 7" 0) +option(ARM_V8 "Force ARMv8 (64 bit) architecture, use with caution if automatic detection fails, but you sure it may work" OFF) +option(ARM_V7 "Force ARMv7 (32 bit) architecture, use with caution if automatic detection fails, but you sure it may work" OFF) option(HWLOC_DEBUG "Enable hwloc debug helpers and log" OFF) @@ -49,11 +61,11 @@ set(HEADERS src/core/config/usage.h src/core/Controller.h src/core/Miner.h + src/core/Taskbar.h src/net/interfaces/IJobResultListener.h src/net/JobResult.h src/net/JobResults.h src/net/Network.h - src/net/NetworkState.h src/net/strategies/DonateStrategy.h src/Summary.h src/version.h @@ -76,10 +88,7 @@ set(HEADERS_CRYPTO src/crypto/cn/hash.h src/crypto/cn/skein_port.h src/crypto/cn/soft_aes.h - src/crypto/common/Algorithm.h - src/crypto/common/Coin.h src/crypto/common/HugePagesInfo.h - src/crypto/common/keccak.h src/crypto/common/MemoryPool.h src/crypto/common/Nonce.h src/crypto/common/portable/mm_malloc.h @@ -101,9 +110,9 @@ set(SOURCES src/core/config/ConfigTransform.cpp src/core/Controller.cpp src/core/Miner.cpp + src/core/Taskbar.cpp src/net/JobResults.cpp src/net/Network.cpp - src/net/NetworkState.cpp src/net/strategies/DonateStrategy.cpp src/Summary.cpp src/xmrig.cpp @@ -116,15 +125,25 @@ set(SOURCES_CRYPTO src/crypto/cn/c_skein.c src/crypto/cn/CnCtx.cpp src/crypto/cn/CnHash.cpp - src/crypto/common/Algorithm.cpp - src/crypto/common/Coin.cpp src/crypto/common/HugePagesInfo.cpp - src/crypto/common/keccak.cpp src/crypto/common/MemoryPool.cpp src/crypto/common/Nonce.cpp src/crypto/common/VirtualMemory.cpp ) +if (CMAKE_C_COMPILER_ID MATCHES GNU) + set_source_files_properties(src/crypto/cn/CnHash.cpp PROPERTIES COMPILE_FLAGS "-Ofast -fno-tree-vectorize") +endif() + +if (WITH_VAES) + add_definitions(-DXMRIG_VAES) + set(HEADERS_CRYPTO "${HEADERS_CRYPTO}" src/crypto/cn/CryptoNight_x86_vaes.h) + set(SOURCES_CRYPTO "${SOURCES_CRYPTO}" src/crypto/cn/CryptoNight_x86_vaes.cpp) + if (CMAKE_C_COMPILER_ID MATCHES GNU OR CMAKE_C_COMPILER_ID MATCHES Clang) + set_source_files_properties(src/crypto/cn/CryptoNight_x86_vaes.cpp PROPERTIES COMPILE_FLAGS "-Ofast -fno-tree-vectorize -mavx2 -mvaes") + endif() +endif() + if (WITH_HWLOC) list(APPEND HEADERS_CRYPTO src/crypto/common/NUMAMemoryPool.h @@ -143,12 +162,16 @@ if (XMRIG_OS_WIN) src/crypto/common/VirtualMemory_win.cpp ) - set(EXTRA_LIBS ws2_32 psapi iphlpapi userenv) + set(EXTRA_LIBS ws2_32 psapi iphlpapi userenv dbghelp) elseif (XMRIG_OS_APPLE) list(APPEND SOURCES_OS src/App_unix.cpp src/crypto/common/VirtualMemory_unix.cpp ) + + find_library(IOKIT_LIBRARY IOKit) + find_library(CORESERVICES_LIBRARY CoreServices) + set(EXTRA_LIBS ${IOKIT_LIBRARY} ${CORESERVICES_LIBRARY}) else() list(APPEND SOURCES_OS src/App_unix.cpp @@ -169,17 +192,18 @@ else() endif() endif() -add_definitions(/D__STDC_FORMAT_MACROS) -add_definitions(/DUNICODE) +add_definitions(-DXMRIG_MINER_PROJECT -DXMRIG_JSON_SINGLE_LINE_ARRAY) +add_definitions(-D__STDC_FORMAT_MACROS -DUNICODE -D_FILE_OFFSET_BITS=64) find_package(UV REQUIRED) include(cmake/flags.cmake) include(cmake/randomx.cmake) include(cmake/argon2.cmake) +include(cmake/kawpow.cmake) +include(cmake/ghostrider.cmake) include(cmake/OpenSSL.cmake) include(cmake/asm.cmake) -include(cmake/cn-gpu.cmake) if (WITH_CN_LITE) add_definitions(/DXMRIG_ALGO_CN_LITE) @@ -193,26 +217,40 @@ if (WITH_CN_PICO) add_definitions(/DXMRIG_ALGO_CN_PICO) endif() +if (WITH_CN_FEMTO) + add_definitions(/DXMRIG_ALGO_CN_FEMTO) +endif() + if (WITH_EMBEDDED_CONFIG) add_definitions(/DXMRIG_FEATURE_EMBEDDED_CONFIG) endif() +include(src/hw/api/api.cmake) +include(src/hw/dmi/dmi.cmake) + include_directories(src) include_directories(src/3rdparty) include_directories(${UV_INCLUDE_DIR}) -if (BUILD_STATIC) - set(CMAKE_EXE_LINKER_FLAGS " -static") -endif() - if (WITH_DEBUG_LOG) add_definitions(/DAPP_DEBUG) endif() -add_executable(${CMAKE_PROJECT_NAME} ${HEADERS} ${SOURCES} ${SOURCES_OS} ${SOURCES_CPUID} ${HEADERS_CRYPTO} ${SOURCES_CRYPTO} ${SOURCES_SYSLOG} ${TLS_SOURCES} ${XMRIG_ASM_SOURCES} ${CN_GPU_SOURCES}) -target_link_libraries(${CMAKE_PROJECT_NAME} ${XMRIG_ASM_LIBRARY} ${OPENSSL_LIBRARIES} ${UV_LIBRARIES} ${EXTRA_LIBS} ${CPUID_LIB} ${ARGON2_LIBRARY}) +add_executable(${CMAKE_PROJECT_NAME} ${HEADERS} ${SOURCES} ${SOURCES_OS} ${HEADERS_CRYPTO} ${SOURCES_CRYPTO} ${SOURCES_SYSLOG} ${TLS_SOURCES} ${XMRIG_ASM_SOURCES}) +target_link_libraries(${CMAKE_PROJECT_NAME} ${XMRIG_ASM_LIBRARY} ${OPENSSL_LIBRARIES} ${UV_LIBRARIES} ${EXTRA_LIBS} ${CPUID_LIB} ${ARGON2_LIBRARY} ${ETHASH_LIBRARY} ${GHOSTRIDER_LIBRARY}) if (WIN32) - add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/bin/WinRing0/WinRing0x64.sys" $) + if (NOT ARM_TARGET) + add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/bin/WinRing0/WinRing0x64.sys" $) + endif() + + add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/scripts/benchmark_1M.cmd" $) + add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/scripts/benchmark_10M.cmd" $) + add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/scripts/pool_mine_example.cmd" $) + add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/scripts/solo_mine_example.cmd" $) + add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/scripts/rtm_ghostrider_example.cmd" $) +endif() + +if (CMAKE_CXX_COMPILER_ID MATCHES Clang AND CMAKE_BUILD_TYPE STREQUAL Release AND NOT CMAKE_GENERATOR STREQUAL Xcode) + add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_STRIP} "$") endif() diff --git a/README.md b/README.md index 99d798f1..b4d40751 100644 --- a/README.md +++ b/README.md @@ -1,119 +1,36 @@ # XMRig -**:warning: [Monero changed PoW algorithm to RandomX on November 30.](https://github.com/xmrig/xmrig/issues/1204)** - [![Github All Releases](https://img.shields.io/github/downloads/xmrig/xmrig/total.svg)](https://github.com/xmrig/xmrig/releases) [![GitHub release](https://img.shields.io/github/release/xmrig/xmrig/all.svg)](https://github.com/xmrig/xmrig/releases) -[![GitHub Release Date](https://img.shields.io/github/release-date-pre/xmrig/xmrig.svg)](https://github.com/xmrig/xmrig/releases) +[![GitHub Release Date](https://img.shields.io/github/release-date/xmrig/xmrig.svg)](https://github.com/xmrig/xmrig/releases) [![GitHub license](https://img.shields.io/github/license/xmrig/xmrig.svg)](https://github.com/xmrig/xmrig/blob/master/LICENSE) [![GitHub stars](https://img.shields.io/github/stars/xmrig/xmrig.svg)](https://github.com/xmrig/xmrig/stargazers) [![GitHub forks](https://img.shields.io/github/forks/xmrig/xmrig.svg)](https://github.com/xmrig/xmrig/network) -XMRig High performance, open source, cross platform RandomX, CryptoNight and Argon2 CPU/GPU miner, with official support for Windows. +XMRig is a high performance, open source, cross platform RandomX, KawPow, CryptoNight and [GhostRider](https://github.com/xmrig/xmrig/tree/master/src/crypto/ghostrider#readme) unified CPU/GPU miner and [RandomX benchmark](https://xmrig.com/benchmark). Official binaries are available for Windows, Linux, macOS and FreeBSD. ## Mining backends -- **CPU** (x64/x86/ARM) +- **CPU** (x86/x64/ARMv7/ARMv8) - **OpenCL** for AMD GPUs. - **CUDA** for NVIDIA GPUs via external [CUDA plugin](https://github.com/xmrig/xmrig-cuda). - - ## Download -* Binary releases: https://github.com/xmrig/xmrig/releases -* Git tree: https://github.com/xmrig/xmrig.git - * Clone with `git clone https://github.com/xmrig/xmrig.git` :hammer: [Build instructions](https://github.com/xmrig/xmrig/wiki/Build). +* **[Binary releases](https://github.com/xmrig/xmrig/releases)** +* **[Build from source](https://xmrig.com/docs/miner/build)** ## Usage -The preferred way to configure the miner is the [JSON config file](src/config.json) as it is more flexible and human friendly. The command line interface does not cover all features, such as mining profiles for different algorithms. Important options can be changed during runtime without miner restart by editing the config file or executing API calls. +The preferred way to configure the miner is the [JSON config file](https://xmrig.com/docs/miner/config) as it is more flexible and human friendly. The [command line interface](https://xmrig.com/docs/miner/command-line-options) does not cover all features, such as mining profiles for different algorithms. Important options can be changed during runtime without miner restart by editing the config file or executing [API](https://xmrig.com/docs/miner/api) calls. -* **[xmrig.com/wizard](https://xmrig.com/wizard)** helps you create initial configuration for the miner. -* **[workers.xmrig.info](http://workers.xmrig.info)** helps manage your miners via HTTP API. - -### Command line options -``` -Network: - -o, --url=URL URL of mining server - -a, --algo=ALGO mining algorithm https://xmrig.com/docs/algorithms - --coin=COIN specify coin instead of algorithm - -u, --user=USERNAME username for mining server - -p, --pass=PASSWORD password for mining server - -O, --userpass=U:P username:password pair for mining server - -k, --keepalive send keepalive packet for prevent timeout (needs pool support) - --nicehash enable nicehash.com support - --rig-id=ID rig identifier for pool-side statistics (needs pool support) - --tls enable SSL/TLS support (needs pool support) - --tls-fingerprint=HEX pool TLS certificate fingerprint for strict certificate pinning - --daemon use daemon RPC instead of pool for solo mining - --daemon-poll-interval=N daemon poll interval in milliseconds (default: 1000) - -r, --retries=N number of times to retry before switch to backup server (default: 5) - -R, --retry-pause=N time to pause between retries (default: 5) - --user-agent set custom user-agent string for pool - --donate-level=N donate level, default 5%% (5 minutes in 100 minutes) - --donate-over-proxy=N control donate over xmrig-proxy feature - -CPU backend: - --no-cpu disable CPU mining backend - -t, --threads=N number of CPU threads - -v, --av=N algorithm variation, 0 auto select - --cpu-affinity set process affinity to CPU core(s), mask 0x3 for cores 0 and 1 - --cpu-priority set process priority (0 idle, 2 normal to 5 highest) - --cpu-max-threads-hint=N maximum CPU threads count (in percentage) hint for autoconfig - --cpu-memory-pool=N number of 2 MB pages for persistent memory pool, -1 (auto), 0 (disable) - --cpu-no-yield prefer maximum hashrate rather than system response/stability - --no-huge-pages disable huge pages support - --asm=ASM ASM optimizations, possible values: auto, none, intel, ryzen, bulldozer - --randomx-init=N thread count to initialize RandomX dataset - --randomx-no-numa disable NUMA support for RandomX - --randomx-mode=MODE RandomX mode: auto, fast, light - --randomx-1gb-pages use 1GB hugepages for dataset (Linux only) - --randomx-wrmsr=N write custom value (0-15) to Intel MSR register 0x1a4 or disable MSR mod (-1) - --randomx-no-rdmsr disable reverting initial MSR values on exit - -API: - --api-worker-id=ID custom worker-id for API - --api-id=ID custom instance ID for API - --http-host=HOST bind host for HTTP API (default: 127.0.0.1) - --http-port=N bind port for HTTP API - --http-access-token=T access token for HTTP API - --http-no-restricted enable full remote access to HTTP API (only if access token set) - -OpenCL backend: - --opencl enable OpenCL mining backend - --opencl-devices=N comma separated list of OpenCL devices to use - --opencl-platform=N OpenCL platform index or name - --opencl-loader=PATH path to OpenCL-ICD-Loader (OpenCL.dll or libOpenCL.so) - --opencl-no-cache disable OpenCL cache - --print-platforms print available OpenCL platforms and exit - -CUDA backend: - --cuda enable CUDA mining backend - --cuda-loader=PATH path to CUDA plugin (xmrig-cuda.dll or libxmrig-cuda.so) - --cuda-devices=N comma separated list of CUDA devices to use - --cuda-bfactor-hint=N bfactor hint for autoconfig (0-12) - --cuda-bsleep-hint=N bsleep hint for autoconfig - --no-nvml disable NVML (NVIDIA Management Library) support - -Logging: - -S, --syslog use system log for output messages - -l, --log-file=FILE log all output to a file - --print-time=N print hashrate report every N seconds - --health-print-time=N print health report every N seconds - --no-color disable colored output - --verbose verbose output - -Misc: - -c, --config=FILE load a JSON-format configuration file - -B, --background run the miner in the background - -V, --version output version information and exit - -h, --help display this help and exit - --dry-run test configuration and exit - --export-topology export hwloc topology to a XML file and exit -``` +* **[Wizard](https://xmrig.com/wizard)** helps you create initial configuration for the miner. +* **[Workers](http://workers.xmrig.info)** helps manage your miners via HTTP API. ## Donations -* Default donation 5% (5 minutes in 100 minutes) can be reduced to 1% via option `donate-level` or disabled in source code. +* Default donation 1% (1 minute in 100 minutes) can be increased via option `donate-level` or disabled in source code. * XMR: `48edfHu7V9Z84YzzMa6fUueoELZ9ZRXq9VetWzYGzKt52XU5xvqgzYnDK9URnRoJMk1j8nLwEVsaSWJ4fhdUyZijBGUicoD` -* BTC: `1P7ujsXeX7GxQwHNnJsRMgAdNkFZmNVqJT` + +## Developers +* **[xmrig](https://github.com/xmrig)** +* **[sech1](https://github.com/SChernykh)** ## Contacts * support@xmrig.com diff --git a/cmake/OpenSSL.cmake b/cmake/OpenSSL.cmake index 7ff83995..84f97d54 100644 --- a/cmake/OpenSSL.cmake +++ b/cmake/OpenSSL.cmake @@ -5,19 +5,43 @@ if (WITH_TLS) set(OPENSSL_USE_STATIC_LIBS TRUE) set(OPENSSL_MSVC_STATIC_RT TRUE) - set(EXTRA_LIBS ${EXTRA_LIBS} Crypt32) + set(EXTRA_LIBS ${EXTRA_LIBS} crypt32) elseif (APPLE) set(OPENSSL_USE_STATIC_LIBS TRUE) endif() + if (BUILD_STATIC) + set(OPENSSL_USE_STATIC_LIBS TRUE) + endif() + + find_package(OpenSSL) if (OPENSSL_FOUND) - set(TLS_SOURCES src/base/net/stratum/Tls.h src/base/net/stratum/Tls.cpp) + set(TLS_SOURCES + src/base/net/stratum/Tls.cpp + src/base/net/stratum/Tls.h + src/base/net/tls/ServerTls.cpp + src/base/net/tls/ServerTls.h + src/base/net/tls/TlsConfig.cpp + src/base/net/tls/TlsConfig.h + src/base/net/tls/TlsContext.cpp + src/base/net/tls/TlsContext.h + src/base/net/tls/TlsGen.cpp + src/base/net/tls/TlsGen.h + ) + include_directories(${OPENSSL_INCLUDE_DIR}) if (WITH_HTTP) - set(TLS_SOURCES ${TLS_SOURCES} src/base/net/http/HttpsClient.h src/base/net/http/HttpsClient.cpp) + set(TLS_SOURCES ${TLS_SOURCES} + src/base/net/https/HttpsClient.cpp + src/base/net/https/HttpsClient.h + src/base/net/https/HttpsContext.cpp + src/base/net/https/HttpsContext.h + src/base/net/https/HttpsServer.cpp + src/base/net/https/HttpsServer.h + ) endif() else() message(FATAL_ERROR "OpenSSL NOT found: use `-DWITH_TLS=OFF` to build without TLS support") @@ -29,5 +53,12 @@ else() set(OPENSSL_LIBRARIES "") remove_definitions(/DXMRIG_FEATURE_TLS) + if (WITH_HTTP) + set(TLS_SOURCES ${TLS_SOURCES} + src/base/net/http/HttpServer.cpp + src/base/net/http/HttpServer.h + ) + endif() + set(CMAKE_PROJECT_NAME "${CMAKE_PROJECT_NAME}-notls") endif() diff --git a/cmake/cn-gpu.cmake b/cmake/cn-gpu.cmake deleted file mode 100644 index 7aa489e6..00000000 --- a/cmake/cn-gpu.cmake +++ /dev/null @@ -1,25 +0,0 @@ -if (WITH_CN_GPU AND CMAKE_SIZEOF_VOID_P EQUAL 8) - - if (XMRIG_ARM) - set(CN_GPU_SOURCES src/crypto/cn/gpu/cn_gpu_arm.cpp) - - if (CMAKE_CXX_COMPILER_ID MATCHES GNU OR CMAKE_CXX_COMPILER_ID MATCHES Clang) - set_source_files_properties(src/crypto/cn/gpu/cn_gpu_arm.cpp PROPERTIES COMPILE_FLAGS "-O3") - endif() - else() - set(CN_GPU_SOURCES src/crypto/cn/gpu/cn_gpu_avx.cpp src/crypto/cn/gpu/cn_gpu_ssse3.cpp) - - if (CMAKE_CXX_COMPILER_ID MATCHES GNU OR CMAKE_CXX_COMPILER_ID MATCHES Clang) - set_source_files_properties(src/crypto/cn/gpu/cn_gpu_avx.cpp PROPERTIES COMPILE_FLAGS "-O3 -mavx2") - set_source_files_properties(src/crypto/cn/gpu/cn_gpu_ssse3.cpp PROPERTIES COMPILE_FLAGS "-O3") - elseif (CMAKE_CXX_COMPILER_ID MATCHES MSVC) - set_source_files_properties(src/crypto/cn/gpu/cn_gpu_avx.cpp PROPERTIES COMPILE_FLAGS "/arch:AVX") - endif() - endif() - - add_definitions(/DXMRIG_ALGO_CN_GPU) -else() - set(CN_GPU_SOURCES "") - - remove_definitions(/DXMRIG_ALGO_CN_GPU) -endif() diff --git a/cmake/cpu.cmake b/cmake/cpu.cmake index 2fdebad8..12dbe9b1 100644 --- a/cmake/cpu.cmake +++ b/cmake/cpu.cmake @@ -1,43 +1,72 @@ +if (CMAKE_SIZEOF_VOID_P EQUAL 8) + set(XMRIG_64_BIT ON) + add_definitions(-DXMRIG_64_BIT) +else() + set(XMRIG_64_BIT OFF) +endif() + if (NOT CMAKE_SYSTEM_PROCESSOR) message(WARNING "CMAKE_SYSTEM_PROCESSOR not defined") endif() +include(CheckCXXCompilerFlag) -if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") - add_definitions(/DRAPIDJSON_SSE2) +if (CMAKE_CXX_COMPILER_ID MATCHES MSVC) + set(VAES_SUPPORTED ON) +else() + CHECK_CXX_COMPILER_FLAG("-mavx2 -mvaes" VAES_SUPPORTED) +endif() + +if (NOT VAES_SUPPORTED) + set(WITH_VAES OFF) +endif() + +if (XMRIG_64_BIT AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") + add_definitions(-DRAPIDJSON_SSE2) +else() + set(WITH_SSE4_1 OFF) + set(WITH_AVX2 OFF) + set(WITH_VAES OFF) +endif() + +add_definitions(-DRAPIDJSON_WRITE_DEFAULT_FLAGS=6) # rapidjson::kWriteNanAndInfFlag | rapidjson::kWriteNanAndInfNullFlag + +if (ARM_V8) + set(ARM_TARGET 8) +elseif (ARM_V7) + set(ARM_TARGET 7) endif() if (NOT ARM_TARGET) - if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64|armv8-a)$") + if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64|ARM64|armv8-a)$") set(ARM_TARGET 8) - elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(armv7|armv7f|armv7s|armv7k|armv7-a|armv7l)$") + elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(armv7|armv7f|armv7s|armv7k|armv7-a|armv7l|armv7ve)$") set(ARM_TARGET 7) endif() endif() if (ARM_TARGET AND ARM_TARGET GREATER 6) - set(XMRIG_ARM ON) - set(WITH_LIBCPUID OFF) - add_definitions(/DXMRIG_ARM) + set(XMRIG_ARM ON) + add_definitions(-DXMRIG_ARM=${ARM_TARGET}) message(STATUS "Use ARM_TARGET=${ARM_TARGET} (${CMAKE_SYSTEM_PROCESSOR})") - include(CheckCXXCompilerFlag) - - if (ARM_TARGET EQUAL 8) - set(XMRIG_ARMv8 ON) - add_definitions(/DXMRIG_ARMv8) - + if (ARM_TARGET EQUAL 8 AND (CMAKE_CXX_COMPILER_ID MATCHES GNU OR CMAKE_CXX_COMPILER_ID MATCHES Clang)) CHECK_CXX_COMPILER_FLAG(-march=armv8-a+crypto XMRIG_ARM_CRYPTO) if (XMRIG_ARM_CRYPTO) - add_definitions(/DXMRIG_ARM_CRYPTO) + add_definitions(-DXMRIG_ARM_CRYPTO) set(ARM8_CXX_FLAGS "-march=armv8-a+crypto") else() set(ARM8_CXX_FLAGS "-march=armv8-a") endif() - elseif (ARM_TARGET EQUAL 7) - set(XMRIG_ARMv7 ON) - add_definitions(/DXMRIG_ARMv7) endif() endif() + +if (WITH_SSE4_1) + add_definitions(-DXMRIG_FEATURE_SSE4_1) +endif() + +if (WITH_AVX2) + add_definitions(-DXMRIG_FEATURE_AVX2) +endif() diff --git a/cmake/flags.cmake b/cmake/flags.cmake index d2bc70d0..9abf212a 100644 --- a/cmake/flags.cmake +++ b/cmake/flags.cmake @@ -10,7 +10,7 @@ if ("${CMAKE_BUILD_TYPE}" STREQUAL "") endif() if (CMAKE_BUILD_TYPE STREQUAL "Release") - add_definitions(/DNDEBUG) + add_definitions(-DNDEBUG) endif() include(CheckSymbolExists) @@ -22,17 +22,17 @@ if (CMAKE_CXX_COMPILER_ID MATCHES GNU) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -fexceptions -fno-rtti -Wno-strict-aliasing -Wno-class-memaccess") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Ofast -s") - if (XMRIG_ARMv8) + if (ARM_TARGET EQUAL 8) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${ARM8_CXX_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ARM8_CXX_FLAGS} -flax-vector-conversions") - elseif (XMRIG_ARMv7) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=neon") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon -flax-vector-conversions") + elseif (ARM_TARGET EQUAL 7) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -march=armv7-a -mfpu=neon -flax-vector-conversions") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=armv7-a -mfpu=neon -flax-vector-conversions") else() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -maes") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -maes") - add_definitions(/DHAVE_ROTR) + add_definitions(-DHAVE_ROTR) endif() if (WIN32) @@ -45,38 +45,33 @@ if (CMAKE_CXX_COMPILER_ID MATCHES GNU) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc -static-libstdc++") endif() - add_definitions(/D_GNU_SOURCE) - - if (${CMAKE_VERSION} VERSION_LESS "3.1.0") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + if (BUILD_STATIC) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static") endif() - #set(CMAKE_C_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -gdwarf-2") - - add_definitions(/DHAVE_BUILTIN_CLEAR_CACHE) + add_definitions(-D_GNU_SOURCE -DHAVE_BUILTIN_CLEAR_CACHE) elseif (CMAKE_CXX_COMPILER_ID MATCHES MSVC) - set(CMAKE_C_FLAGS_RELEASE "/MT /O2 /Oi /DNDEBUG /GL") - set(CMAKE_CXX_FLAGS_RELEASE "/MT /O2 /Oi /DNDEBUG /GL") + set(CMAKE_C_FLAGS_RELEASE "/MP /MT /O2 /Oi /DNDEBUG /GL") + set(CMAKE_CXX_FLAGS_RELEASE "/MP /MT /O2 /Oi /DNDEBUG /GL") - add_definitions(/D_CRT_SECURE_NO_WARNINGS) - add_definitions(/D_CRT_NONSTDC_NO_WARNINGS) - add_definitions(/DNOMINMAX) - add_definitions(/DHAVE_ROTR) + set(CMAKE_C_FLAGS_RELWITHDEBINFO "/MP /Ob1 /Zi /DRELWITHDEBINFO") + set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "/MP /Ob1 /Zi /DRELWITHDEBINFO") + + add_definitions(-D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_WARNINGS -DNOMINMAX -DHAVE_ROTR) elseif (CMAKE_CXX_COMPILER_ID MATCHES Clang) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall") - set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -Ofast -funroll-loops -fmerge-all-constants") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -funroll-loops -fmerge-all-constants") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -fexceptions -fno-rtti -Wno-missing-braces") - set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Ofast -funroll-loops -fmerge-all-constants") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -fexceptions -fno-rtti") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -funroll-loops -fmerge-all-constants") - if (XMRIG_ARMv8) + if (ARM_TARGET EQUAL 8) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${ARM8_CXX_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ARM8_CXX_FLAGS}") - elseif (XMRIG_ARMv7) + elseif (ARM_TARGET EQUAL 7) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=neon -march=${CMAKE_SYSTEM_PROCESSOR}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon -march=${CMAKE_SYSTEM_PROCESSOR}") else() @@ -85,15 +80,18 @@ elseif (CMAKE_CXX_COMPILER_ID MATCHES Clang) check_symbol_exists("_rotr" "x86intrin.h" HAVE_ROTR) if (HAVE_ROTR) - add_definitions(/DHAVE_ROTR) + add_definitions(-DHAVE_ROTR) endif() endif() + if ((WIN32 AND ARM_TARGET) OR BUILD_STATIC) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static") + endif() endif() if (NOT WIN32) check_symbol_exists("__builtin___clear_cache" "stdlib.h" HAVE_BUILTIN_CLEAR_CACHE) if (HAVE_BUILTIN_CLEAR_CACHE) - add_definitions(/DHAVE_BUILTIN_CLEAR_CACHE) + add_definitions(-DHAVE_BUILTIN_CLEAR_CACHE) endif() endif() diff --git a/cmake/ghostrider.cmake b/cmake/ghostrider.cmake new file mode 100644 index 00000000..3bc935b1 --- /dev/null +++ b/cmake/ghostrider.cmake @@ -0,0 +1,8 @@ +if (WITH_GHOSTRIDER) + add_definitions(/DXMRIG_ALGO_GHOSTRIDER) + add_subdirectory(src/crypto/ghostrider) + set(GHOSTRIDER_LIBRARY ghostrider) +else() + remove_definitions(/DXMRIG_ALGO_GHOSTRIDER) + set(GHOSTRIDER_LIBRARY "") +endif() diff --git a/cmake/kawpow.cmake b/cmake/kawpow.cmake new file mode 100644 index 00000000..3c160266 --- /dev/null +++ b/cmake/kawpow.cmake @@ -0,0 +1,19 @@ +if (WITH_KAWPOW) + add_definitions(/DXMRIG_ALGO_KAWPOW) + + list(APPEND HEADERS_CRYPTO + src/crypto/kawpow/KPCache.h + src/crypto/kawpow/KPHash.h + ) + + list(APPEND SOURCES_CRYPTO + src/crypto/kawpow/KPCache.cpp + src/crypto/kawpow/KPHash.cpp + ) + + add_subdirectory(src/3rdparty/libethash) + set(ETHASH_LIBRARY ethash) +else() + remove_definitions(/DXMRIG_ALGO_KAWPOW) + set(ETHASH_LIBRARY "") +endif() diff --git a/cmake/os.cmake b/cmake/os.cmake index 0270cc93..8f70e9f4 100644 --- a/cmake/os.cmake +++ b/cmake/os.cmake @@ -15,31 +15,37 @@ else() set(XMRIG_OS_ANDROID ON) elseif(CMAKE_SYSTEM_NAME MATCHES "Linux") set(XMRIG_OS_LINUX ON) - elseif(CMAKE_SYSTEM_NAME STREQUAL FreeBSD) + elseif(CMAKE_SYSTEM_NAME STREQUAL FreeBSD OR CMAKE_SYSTEM_NAME STREQUAL DragonFly) set(XMRIG_OS_FREEBSD ON) endif() endif() - if (XMRIG_OS_WIN) - add_definitions(/DWIN32) - add_definitions(/DXMRIG_OS_WIN) + add_definitions(-DWIN32 -DXMRIG_OS_WIN) elseif(XMRIG_OS_APPLE) - add_definitions(/DXMRIG_OS_APPLE) + add_definitions(-DXMRIG_OS_APPLE) if (XMRIG_OS_IOS) - add_definitions(/DXMRIG_OS_IOS) + add_definitions(-DXMRIG_OS_IOS) else() - add_definitions(/DXMRIG_OS_MACOS) + add_definitions(-DXMRIG_OS_MACOS) + endif() + + if (XMRIG_ARM) + set(WITH_SECURE_JIT ON) endif() elseif(XMRIG_OS_UNIX) - add_definitions(/DXMRIG_OS_UNIX) + add_definitions(-DXMRIG_OS_UNIX) if (XMRIG_OS_ANDROID) - add_definitions(/DXMRIG_OS_ANDROID) + add_definitions(-DXMRIG_OS_ANDROID) elseif (XMRIG_OS_LINUX) - add_definitions(/DXMRIG_OS_LINUX) + add_definitions(-DXMRIG_OS_LINUX) elseif (XMRIG_OS_FREEBSD) - add_definitions(/DXMRIG_OS_FREEBSD) + add_definitions(-DXMRIG_OS_FREEBSD) endif() endif() + +if (WITH_SECURE_JIT) + add_definitions(-DXMRIG_SECURE_JIT) +endif() diff --git a/cmake/randomx.cmake b/cmake/randomx.cmake index 83180710..a50e078f 100644 --- a/cmake/randomx.cmake +++ b/cmake/randomx.cmake @@ -1,5 +1,20 @@ if (WITH_RANDOMX) + include(CheckSymbolExists) + + if (WIN32) + check_symbol_exists(_aligned_malloc "stdlib.h" HAVE_ALIGNED_MALLOC) + if (HAVE_ALIGNED_MALLOC) + add_compile_definitions(HAVE_ALIGNED_MALLOC) + endif() + else() + check_symbol_exists(posix_memalign "stdlib.h" HAVE_POSIX_MEMALIGN) + if (HAVE_POSIX_MEMALIGN) + add_compile_definitions(HAVE_POSIX_MEMALIGN) + endif() + endif() + add_definitions(/DXMRIG_ALGO_RANDOMX) + set(WITH_ARGON2 ON) list(APPEND HEADERS_CRYPTO src/crypto/rx/Rx.h @@ -16,8 +31,6 @@ if (WITH_RANDOMX) list(APPEND SOURCES_CRYPTO src/crypto/randomx/aes_hash.cpp src/crypto/randomx/allocator.cpp - src/crypto/randomx/argon2_core.c - src/crypto/randomx/argon2_ref.c src/crypto/randomx/blake2_generator.cpp src/crypto/randomx/blake2/blake2b.c src/crypto/randomx/bytecode_machine.cpp @@ -43,13 +56,13 @@ if (WITH_RANDOMX) src/crypto/rx/RxVm.cpp ) - if (CMAKE_C_COMPILER_ID MATCHES MSVC) + if (WITH_ASM AND CMAKE_C_COMPILER_ID MATCHES MSVC) enable_language(ASM_MASM) list(APPEND SOURCES_CRYPTO src/crypto/randomx/jit_compiler_x86_static.asm src/crypto/randomx/jit_compiler_x86.cpp ) - elseif (NOT XMRIG_ARM AND CMAKE_SIZEOF_VOID_P EQUAL 8) + elseif (WITH_ASM AND NOT XMRIG_ARM AND CMAKE_SIZEOF_VOID_P EQUAL 8) list(APPEND SOURCES_CRYPTO src/crypto/randomx/jit_compiler_x86_static.S src/crypto/randomx/jit_compiler_x86.cpp @@ -62,7 +75,31 @@ if (WITH_RANDOMX) src/crypto/randomx/jit_compiler_a64.cpp ) # cheat because cmake and ccache hate each other - set_property(SOURCE src/crypto/randomx/jit_compiler_a64_static.S PROPERTY LANGUAGE C) + if (CMAKE_GENERATOR STREQUAL Xcode) + set_property(SOURCE src/crypto/randomx/jit_compiler_a64_static.S PROPERTY LANGUAGE ASM) + else() + set_property(SOURCE src/crypto/randomx/jit_compiler_a64_static.S PROPERTY LANGUAGE C) + endif() + else() + list(APPEND SOURCES_CRYPTO + src/crypto/randomx/jit_compiler_fallback.cpp + ) + endif() + + if (WITH_SSE4_1) + list(APPEND SOURCES_CRYPTO src/crypto/randomx/blake2/blake2b_sse41.c) + + if (CMAKE_C_COMPILER_ID MATCHES GNU OR CMAKE_C_COMPILER_ID MATCHES Clang) + set_source_files_properties(src/crypto/randomx/blake2/blake2b_sse41.c PROPERTIES COMPILE_FLAGS "-Ofast -msse4.1") + endif() + endif() + + if (WITH_AVX2) + list(APPEND SOURCES_CRYPTO src/crypto/randomx/blake2/avx2/blake2b_avx2.c) + + if (CMAKE_C_COMPILER_ID MATCHES GNU OR CMAKE_C_COMPILER_ID MATCHES Clang) + set_source_files_properties(src/crypto/randomx/blake2/avx2/blake2b_avx2.c PROPERTIES COMPILE_FLAGS "-Ofast -mavx2") + endif() endif() if (CMAKE_CXX_COMPILER_ID MATCHES Clang) @@ -85,18 +122,41 @@ if (WITH_RANDOMX) message("-- WITH_MSR=ON") if (XMRIG_OS_WIN) - list(APPEND SOURCES_CRYPTO src/crypto/rx/Rx_win.cpp) + list(APPEND SOURCES_CRYPTO + src/crypto/rx/RxFix_win.cpp + src/hw/msr/Msr_win.cpp + ) elseif (XMRIG_OS_LINUX) - list(APPEND SOURCES_CRYPTO src/crypto/rx/Rx_linux.cpp) + list(APPEND SOURCES_CRYPTO + src/crypto/rx/RxFix_linux.cpp + src/hw/msr/Msr_linux.cpp + ) endif() - list(APPEND HEADERS_CRYPTO src/crypto/rx/msr/MsrItem.h) - list(APPEND SOURCES_CRYPTO src/crypto/rx/msr/MsrItem.cpp) + list(APPEND HEADERS_CRYPTO + src/crypto/rx/RxFix.h + src/crypto/rx/RxMsr.h + src/hw/msr/Msr.h + src/hw/msr/MsrItem.h + ) + + list(APPEND SOURCES_CRYPTO + src/crypto/rx/RxMsr.cpp + src/hw/msr/Msr.cpp + src/hw/msr/MsrItem.cpp + ) else() remove_definitions(/DXMRIG_FEATURE_MSR) remove_definitions(/DXMRIG_FIX_RYZEN) message("-- WITH_MSR=OFF") endif() + + if (WITH_PROFILING) + add_definitions(/DXMRIG_FEATURE_PROFILING) + + list(APPEND HEADERS_CRYPTO src/crypto/rx/Profiler.h) + list(APPEND SOURCES_CRYPTO src/crypto/rx/Profiler.cpp) + endif() else() remove_definitions(/DXMRIG_ALGO_RANDOMX) endif() diff --git a/doc/ALGORITHMS.md b/doc/ALGORITHMS.md index 11c84bc8..de3828a0 100644 --- a/doc/ALGORITHMS.md +++ b/doc/ALGORITHMS.md @@ -6,38 +6,39 @@ Algorithm can be defined in 3 ways: 2. Per pool `coin` option, currently only usable values for this option is `monero` and `arqma`. 3. Per pool `algo` option. -Option `coin` useful for pools without algorithm negotiation support or daemon to allow automatically switch algorithm in next hard fork. +Option `coin` useful for pools without [algorithm negotiation](https://xmrig.com/docs/extensions/algorithm-negotiation) support or daemon to allow automatically switch algorithm in next hard fork. If you use xmrig-proxy don't need specify algorithm on miner side. ## Algorithm names -| Name | Memory | Version | Notes | -|------|--------|---------|-------| -| `rx/sfx` | 2 MB | 5.4.0+ | RandomSFX (RandomX variant for Safex). | -| `rx/v` | 2 MB | 5.4.0+ | RandomV (RandomX variant for new MoneroV). | -| `rx/arq` | 256 KB | 4.3.0+ | RandomARQ (RandomX variant for ArQmA). | -| `rx/0` | 2 MB | 3.2.0+ | RandomX (Monero). | -| `argon2/chukwa` | 512 KB | 3.1.0+ | Argon2id (Chukwa). | -| `argon2/wrkz` | 256 KB | 3.1.0+ | Argon2id (WRKZ) | -| `rx/wow` | 1 MB | 3.0.0+ | RandomWOW (RandomX variant for Wownero). | -| `rx/loki` | 2 MB | 3.0.0+ | RandomXL (RandomX variant for Loki). | -| `cn/fast` | 2 MB | 3.0.0+ | CryptoNight variant 1 with half iterations. | -| `cn/rwz` | 2 MB | 2.14.0+ | CryptoNight variant 2 with 3/4 iterations and reversed shuffle operation. | -| `cn/zls` | 2 MB | 2.14.0+ | CryptoNight variant 2 with 3/4 iterations. | -| `cn/double` | 2 MB | 2.14.0+ | CryptoNight variant 2 with double iterations. | -| `cn/r` | 2 MB | 2.13.0+ | CryptoNightR (Monero's variant 4). | -| `cn/gpu` | 2 MB | 2.11.0+ | CryptoNight-GPU. | -| `cn-pico` | 256 KB | 2.10.0+ | CryptoNight-Pico. | -| `cn/half` | 2 MB | 2.9.0+ | CryptoNight variant 2 with half iterations. | -| `cn/2` | 2 MB | 2.8.0+ | CryptoNight variant 2. | -| `cn/xao` | 2 MB | 2.6.4+ | CryptoNight variant 0 (modified). | -| `cn/rto` | 2 MB | 2.6.4+ | CryptoNight variant 1 (modified). | -| `cn-heavy/tube` | 4 MB | 2.6.4+ | CryptoNight-Heavy (modified). | -| `cn-heavy/xhv` | 4 MB | 2.6.3+ | CryptoNight-Heavy (modified). | -| `cn-heavy/0` | 4 MB | 2.6.0+ | CryptoNight-Heavy. | -| `cn/1` | 2 MB | 2.5.0+ | CryptoNight variant 1. | -| `cn-lite/1` | 1 MB | 2.5.0+ | CryptoNight-Lite variant 1. | -| `cn-lite/0` | 1 MB | 0.8.0+ | CryptoNight-Lite variant 0. | -| `cn/0` | 2 MB | 0.5.0+ | CryptoNight (original). | +| Name | Memory | Version | Description | Notes | +|------|--------|---------|-------------|-------| +| `kawpow` | - | 6.0.0+ | KawPow (Ravencoin) | GPU only | +| `astrobwt` | 20 MB | 5.8.0+ | AstroBWT (Dero). | | +| `cn-pico/tlo` | 256 KB | 5.5.0+ | CryptoNight-Pico (Talleo). | | +| `rx/sfx` | 2 MB | 5.4.0+ | RandomSFX (RandomX variant for Safex). | | +| `rx/arq` | 256 KB | 4.3.0+ | RandomARQ (RandomX variant for ArQmA). | | +| `rx/0` | 2 MB | 3.2.0+ | RandomX (Monero). | | +| `argon2/chukwa` | 512 KB | 3.1.0+ | Argon2id (Chukwa). | CPU only | +| `argon2/wrkz` | 256 KB | 3.1.0+ | Argon2id (WRKZ) | CPU only | +| `rx/wow` | 1 MB | 3.0.0+ | RandomWOW (RandomX variant for Wownero). | | +| `rx/loki` | 2 MB | 3.0.0+ | RandomXL (RandomX variant for Loki). | | +| `cn/fast` | 2 MB | 3.0.0+ | CryptoNight variant 1 with half iterations. | | +| `cn/rwz` | 2 MB | 2.14.0+ | CryptoNight variant 2 with 3/4 iterations and reversed shuffle operation. | | +| `cn/zls` | 2 MB | 2.14.0+ | CryptoNight variant 2 with 3/4 iterations. | | +| `cn/double` | 2 MB | 2.14.0+ | CryptoNight variant 2 with double iterations. | | +| `cn/r` | 2 MB | 2.13.0+ | CryptoNightR (Monero's variant 4). | | +| `cn-pico` | 256 KB | 2.10.0+ | CryptoNight-Pico. | | +| `cn/half` | 2 MB | 2.9.0+ | CryptoNight variant 2 with half iterations. | | +| `cn/2` | 2 MB | 2.8.0+ | CryptoNight variant 2. | | +| `cn/xao` | 2 MB | 2.6.4+ | CryptoNight variant 0 (modified). | | +| `cn/rto` | 2 MB | 2.6.4+ | CryptoNight variant 1 (modified). | | +| `cn-heavy/tube` | 4 MB | 2.6.4+ | CryptoNight-Heavy (modified). | | +| `cn-heavy/xhv` | 4 MB | 2.6.3+ | CryptoNight-Heavy (modified). | | +| `cn-heavy/0` | 4 MB | 2.6.0+ | CryptoNight-Heavy. | | +| `cn/1` | 2 MB | 2.5.0+ | CryptoNight variant 1. | | +| `cn-lite/1` | 1 MB | 2.5.0+ | CryptoNight-Lite variant 1. | | +| `cn-lite/0` | 1 MB | 0.8.0+ | CryptoNight-Lite variant 0. | | +| `cn/0` | 2 MB | 0.5.0+ | CryptoNight (original). | | ## Migration to v3 Since version 3 mining [algorithm](#algorithm-names) should specified for each pool separately (`algo` option), earlier versions was use one global `algo` option and per pool `variant` option (this option was removed in v3). If your pool support [mining algorithm negotiation](https://github.com/xmrig/xmrig-proxy/issues/168) you may not specify this option at all. diff --git a/doc/BENCHMARK.md b/doc/BENCHMARK.md new file mode 100644 index 00000000..63b67926 --- /dev/null +++ b/doc/BENCHMARK.md @@ -0,0 +1,29 @@ +# Embedded benchmark + +You can run with XMRig with the following commands: +``` +xmrig --bench=1M +xmrig --bench=10M +xmrig --bench=1M -a rx/wow +xmrig --bench=10M -a rx/wow +``` +This will run between 1 and 10 million RandomX hashes, depending on `bench` parameter, and print the time it took. First two commands use Monero variant (2 MB per thread, best for Zen2/Zen3 CPUs), second two commands use Wownero variant (1 MB per thread, useful for Intel and 1st gen Zen/Zen+ CPUs). + +Checksum of all the hashes will be also printed to check stability of your hardware: if it's green then it's correct, if it's red then there was hardware error during computation. No Internet connection is required for the benchmark. + +Double check that you see `Huge pages 100%` both for dataset and for all threads, and also check for `msr register values ... has been set successfully` - without this result will be far from the best. Running as administrator is required for MSR and huge pages to be set up properly. + +![Benchmark example](https://i.imgur.com/PST3BYc.png) + +### Benchmark with custom config + +You can run benchmark with any configuration you want. Just start without command line parameteres, use regular config.json and add `"benchmark":"1M",` on the next line after pool url. + +# Stress test + +You can also run continuous stress-test that is as close to the real RandomX mining as possible and doesn't require any configuration: +``` +xmrig --stress +xmrig --stress -a rx/wow +``` +This will require Internet connection and will run indefinitely. \ No newline at end of file diff --git a/doc/CHANGELOG_OLD.md b/doc/CHANGELOG_OLD.md index 70059190..a799cb38 100644 --- a/doc/CHANGELOG_OLD.md +++ b/doc/CHANGELOG_OLD.md @@ -256,7 +256,7 @@ # v2.8.0 - **[#753](https://github.com/xmrig/xmrig/issues/753) Added new algorithm [CryptoNight variant 2](https://github.com/xmrig/xmrig/issues/753) for Monero fork, thanks [@SChernykh](https://github.com/SChernykh).** - - Added global and per thread option `"asm"` and and command line equivalent. + - Added global and per thread option `"asm"` and command line equivalent. - **[#758](https://github.com/xmrig/xmrig/issues/758) Added SSL/TLS support for secure connections to pools.** - Added per pool options `"tls"` and `"tls-fingerprint"` and command line equivalents. - [#767](https://github.com/xmrig/xmrig/issues/767) Added config autosave feature, same with GPU miners. diff --git a/doc/CPU.md b/doc/CPU.md index 385af6ad..9cd51b90 100644 --- a/doc/CPU.md +++ b/doc/CPU.md @@ -1,3 +1,5 @@ +**:warning: Recent version of this page https://xmrig.com/docs/miner/config/cpu.** + # CPU backend All CPU related settings contains in one `cpu` object in config file, CPU backend allow specify multiple profiles and allow switch between them without restrictions by pool request or config change. Default auto-configuration create reasonable minimum of profiles which cover all supported algorithms. @@ -75,6 +77,35 @@ Each number represent one thread and means CPU affinity, this is default format ``` Internal format, but can be user defined. +## RandomX options + +#### `init` +Thread count to initialize RandomX dataset. Auto-detect (`-1`) or any number greater than 0 to use that many threads. + +#### `init-avx2` +Use AVX2 for dataset initialization. Faster on some CPUs. Auto-detect (`-1`), disabled (`0`), always enabled on CPUs that support AVX2 (`1`). + +#### `mode` +RandomX mining mode: `auto`, `fast` (2 GB memory), `light` (256 MB memory). + +#### `1gb-pages` +Use 1GB hugepages for RandomX dataset (Linux only). Enabled (`true`) or disabled (`false`). It gives 1-3% speedup. + +#### `wrmsr` +[MSR mod](https://xmrig.com/docs/miner/randomx-optimization-guide/msr). Enabled (`true`) or disabled (`false`). It gives up to 15% speedup depending on your system. _(**Note**: Userspace MSR writes are no longer enabled by default; the flag `msr.allow_writes=on` must be set for Linux Kernels 5.9 and after.)_ + +#### `rdmsr` +Restore MSR register values to their original values on exit. Used together with `wrmsr`. Enabled (`true`) or disabled (`false`). + +#### `cache_qos` +[Cache QoS](https://xmrig.com/docs/miner/randomx-optimization-guide/qos). Enabled (`true`) or disabled (`false`). It's useful when you can't or don't want to mine on all CPU cores to make mining hashrate more stable. + +#### `numa` +NUMA support (better hashrate on multi-CPU servers and Ryzen Threadripper 1xxx/2xxx). Enabled (`true`) or disabled (`false`). + +#### `scratchpad_prefetch_mode` +Which instruction to use in RandomX loop to prefetch data from scratchpad. `1` is default and fastest in most cases. Can be off (`0`), `prefetcht0` instruction (`1`), `prefetchnta` instruction (`2`, a bit faster on Coffee Lake and a few other CPUs), `mov` instruction (`3`). + ## Shared options #### `enabled` @@ -83,23 +114,32 @@ Enable (`true`) or disable (`false`) CPU backend, by default `true`. #### `huge-pages` Enable (`true`) or disable (`false`) huge pages support, by default `true`. +#### `huge-pages-jit` +Enable (`true`) or disable (`false`) huge pages support for RandomX JIT code, by default `false`. It gives a very small boost on Ryzen CPUs, but hashrate is unstable between launches. Use with caution. + #### `hw-aes` Force enable (`true`) or disable (`false`) hardware AES support. Default value `null` means miner autodetect this feature. Usually don't need change this option, this option useful for some rare cases when miner can't detect hardware AES, but it available. If you force enable this option, but your hardware not support it, miner will crash. #### `priority` -Mining threads priority, value from `1` (lowest priority) to `5` (highest possible priority). Default value `null` means miner don't change threads priority at all. +Mining threads priority, value from `1` (lowest priority) to `5` (highest possible priority). Default value `null` means miner don't change threads priority at all. Setting priority higher than 2 can make your PC unresponsive. + +#### `memory-pool` (since v4.3.0) +Use continuous, persistent memory block for mining threads, useful for preserve huge pages allocation while algorithm switching. Possible values `false` (feature disabled, by default) or `true` or specific count of 2 MB huge pages. It helps to avoid loosing huge pages for scratchpads when RandomX dataset is updated and mining threads restart after a 2-3 days of mining. + +#### `yield` (since v5.1.1) +Prefer system better system response/stability `true` (default value) or maximum hashrate `false`. #### `asm` Enable/configure or disable ASM optimizations. Possible values: `true`, `false`, `"intel"`, `"ryzen"`, `"bulldozer"`. #### `argon2-impl` (since v3.1.0) -Allow override automatically detected Argon2 implementation, this option added mostly for debug purposes, default value `null` means autodetect. Other possible values: `"x86_64"`, `"SSE2"`, `"SSSE3"`, `"XOP"`, `"AVX2"`, `"AVX-512F"`. Manual selection has no safe guards, if you CPU not support required instuctions, miner will crash. +Allow override automatically detected Argon2 implementation, this option added mostly for debug purposes, default value `null` means autodetect. This is used in RandomX dataset initialization and also in some other mining algorithms. Other possible values: `"x86_64"`, `"SSE2"`, `"SSSE3"`, `"XOP"`, `"AVX2"`, `"AVX-512F"`. Manual selection has no safe guards - if your CPU doesn't support required instuctions, miner will crash. + +#### `astrobwt-max-size` +AstroBWT algorithm: skip hashes with large stage 2 size, default: `550`, min: `400`, max: `1200`. Optimal value depends on your CPU/GPU + +#### `astrobwt-avx2` +AstroBWT algorithm: use AVX2 code. It's faster on some CPUs and slower on other #### `max-threads-hint` (since v4.2.0) Maximum CPU threads count (in percentage) hint for autoconfig. [CPU_MAX_USAGE.md](CPU_MAX_USAGE.md) - -#### `memory-pool` (since v4.3.0) -Use continuous, persistent memory block for mining threads, useful for preserve huge pages allocation while algorithm swithing. Possible values `false` (feature disabled, by default) or `true` or specific count of 2 MB huge pages. - -#### `yield` (since v5.1.1) -Prefer system better system response/stability `true` (default value) or maximum hashrate `false`. diff --git a/doc/build/CMAKE_OPTIONS.md b/doc/build/CMAKE_OPTIONS.md index 654299de..81e3914f 100644 --- a/doc/build/CMAKE_OPTIONS.md +++ b/doc/build/CMAKE_OPTIONS.md @@ -6,7 +6,6 @@ * **`-DWITH_CN_LITE=OFF`** disable all CryptoNight-Lite algorithms (`cn-lite/0`, `cn-lite/1`). * **`-DWITH_CN_HEAVY=OFF`** disable all CryptoNight-Heavy algorithms (`cn-heavy/0`, `cn-heavy/xhv`, `cn-heavy/tube`). * **`-DWITH_CN_PICO=OFF`** disable CryptoNight-Pico algorithm (`cn-pico`). -* **`-DWITH_CN_GPU=OFF`** disable CryptoNight-GPU algorithm (`cn/gpu`). * **`-DWITH_RANDOMX=OFF`** disable RandomX algorithms (`rx/loki`, `rx/wow`). * **`-DWITH_ARGON2=OFF`** disable Argon2 algorithms (`argon2/chukwa`, `argon2/wrkz`). @@ -23,6 +22,7 @@ This feature add external dependency to libhwloc (1.10.0+) (except MSVC builds). * **`-DWITH_EMBEDDED_CONFIG=ON`** Enable [embedded](https://github.com/xmrig/xmrig/issues/957) config support. * **`-DWITH_OPENCL=OFF`** Disable OpenCL backend. * **`-DWITH_CUDA=OFF`** Disable CUDA backend. +* **`-DWITH_SSE4_1=OFF`** Disable SSE 4.1 for Blake2 (useful for arm builds). ## Debug options diff --git a/doc/releases/5_0_1/SHA256SUMS b/doc/releases/5_0_1/SHA256SUMS deleted file mode 100644 index 1d94745a..00000000 --- a/doc/releases/5_0_1/SHA256SUMS +++ /dev/null @@ -1,5 +0,0 @@ -6bb1a2e3a0fbca5195be6022f2a9fbff8a353c37c7542e7ab89420cb45b64505 xmrig-5.0.1-gcc-win32.zip -24dba9ec281acfb2ea2c401ebd0e4e2d1f1ee5fd557da5ff3c7049020c1f78b6 xmrig-5.0.1-gcc-win64.zip -86d65c6693ec9e35cd7547329580638b85c9eb0cf8383892a1c15199de5b556f xmrig-5.0.1-msvc-cuda10_1-win64.zip -0fbfe518b1c4b6993b0f66ff01302626375b15620ccf8f64d6fb97845068ffca xmrig-5.0.1-msvc-win64.zip -aa34890738a3494de2fa0e44db346937fea7339852f5f10b5d4655f95e2d8f1f xmrig-5.0.1-xenial-x64.tar.gz diff --git a/doc/releases/5_0_1/SHA256SUMS.sig b/doc/releases/5_0_1/SHA256SUMS.sig deleted file mode 100644 index 678e2e6b..00000000 --- a/doc/releases/5_0_1/SHA256SUMS.sig +++ /dev/null @@ -1,11 +0,0 @@ ------BEGIN PGP SIGNATURE----- - -iQEzBAABCgAdFiEEmsTOqOZuNaXHzdwbRGpTY4vpRAkFAl3VcsoACgkQRGpTY4vp -RAm9vQgA1MyTUU2jley2TCYLUzQy2Fffc8fbXYv64r44jbWOjC/6qo2iIlRgPhIc -oVyPKr5TYS3QjDzCEm8IvozS0YudS6soESbPzqDonboK8pd0K4bsML9TQY2feV7A -NL5vln0rfVHp1wxLLrQpfBqAgvJUXEyaHece6gFQN79JOGhEo2bHL2NyrOl+FViS -b2BaMtXq410Fh+XT6ShnOaG/2EuO8ZqSGdCO6A/2LHQw1UY+mZiCvue6P6B06HmB -WD/urOv38V389v+V+Sp4UlEW6VpBOOjvtChoVWtLt+tKzydrnt2EmoWWWg475pka -4G6whHuMWS8CTt5/PDhJpvVXNQTIOw== -=C764 ------END PGP SIGNATURE----- diff --git a/scripts/benchmark_10M.cmd b/scripts/benchmark_10M.cmd new file mode 100644 index 00000000..833f065c --- /dev/null +++ b/scripts/benchmark_10M.cmd @@ -0,0 +1,4 @@ +@echo off +cd /d "%~dp0" +xmrig.exe --bench=10M --submit +pause diff --git a/scripts/benchmark_1M.cmd b/scripts/benchmark_1M.cmd new file mode 100644 index 00000000..b106a1bc --- /dev/null +++ b/scripts/benchmark_1M.cmd @@ -0,0 +1,4 @@ +@echo off +cd /d "%~dp0" +xmrig.exe --bench=1M --submit +pause diff --git a/scripts/build.hwloc.sh b/scripts/build.hwloc.sh new file mode 100755 index 00000000..f4a2c41a --- /dev/null +++ b/scripts/build.hwloc.sh @@ -0,0 +1,23 @@ +#!/bin/sh -e + +HWLOC_VERSION_MAJOR="2" +HWLOC_VERSION_MINOR="12" +HWLOC_VERSION_PATCH="1" + +HWLOC_VERSION="${HWLOC_VERSION_MAJOR}.${HWLOC_VERSION_MINOR}.${HWLOC_VERSION_PATCH}" + +mkdir -p deps +mkdir -p deps/include +mkdir -p deps/lib + +mkdir -p build && cd build + +wget https://download.open-mpi.org/release/hwloc/v${HWLOC_VERSION_MAJOR}.${HWLOC_VERSION_MINOR}/hwloc-${HWLOC_VERSION}.tar.gz -O hwloc-${HWLOC_VERSION}.tar.gz +tar -xzf hwloc-${HWLOC_VERSION}.tar.gz + +cd hwloc-${HWLOC_VERSION} +./configure --disable-shared --enable-static --disable-io --disable-libudev --disable-libxml2 +make -j$(nproc || sysctl -n hw.ncpu || sysctl -n hw.logicalcpu) +cp -fr include ../../deps +cp hwloc/.libs/libhwloc.a ../../deps/lib +cd .. diff --git a/scripts/build.hwloc1.sh b/scripts/build.hwloc1.sh new file mode 100755 index 00000000..82572743 --- /dev/null +++ b/scripts/build.hwloc1.sh @@ -0,0 +1,19 @@ +#!/bin/sh -e + +HWLOC_VERSION="1.11.13" + +mkdir -p deps +mkdir -p deps/include +mkdir -p deps/lib + +mkdir -p build && cd build + +wget https://download.open-mpi.org/release/hwloc/v1.11/hwloc-${HWLOC_VERSION}.tar.gz -O hwloc-${HWLOC_VERSION}.tar.gz +tar -xzf hwloc-${HWLOC_VERSION}.tar.gz + +cd hwloc-${HWLOC_VERSION} +./configure --disable-shared --enable-static --disable-io --disable-libudev --disable-libxml2 +make -j$(nproc || sysctl -n hw.ncpu || sysctl -n hw.logicalcpu) +cp -fr include ../../deps +cp src/.libs/libhwloc.a ../../deps/lib +cd .. \ No newline at end of file diff --git a/scripts/build.libressl.sh b/scripts/build.libressl.sh new file mode 100755 index 00000000..6dde9faa --- /dev/null +++ b/scripts/build.libressl.sh @@ -0,0 +1,20 @@ +#!/bin/sh -e + +LIBRESSL_VERSION="3.5.2" + +mkdir -p deps +mkdir -p deps/include +mkdir -p deps/lib + +mkdir -p build && cd build + +wget https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-${LIBRESSL_VERSION}.tar.gz -O libressl-${LIBRESSL_VERSION}.tar.gz +tar -xzf libressl-${LIBRESSL_VERSION}.tar.gz + +cd libressl-${LIBRESSL_VERSION} +./configure --disable-shared +make -j$(nproc || sysctl -n hw.ncpu || sysctl -n hw.logicalcpu) +cp -fr include ../../deps +cp crypto/.libs/libcrypto.a ../../deps/lib +cp ssl/.libs/libssl.a ../../deps/lib +cd .. diff --git a/scripts/build.openssl.sh b/scripts/build.openssl.sh new file mode 100755 index 00000000..62d2dba0 --- /dev/null +++ b/scripts/build.openssl.sh @@ -0,0 +1,20 @@ +#!/bin/sh -e + +OPENSSL_VERSION="1.1.1u" + +mkdir -p deps +mkdir -p deps/include +mkdir -p deps/lib + +mkdir -p build && cd build + +wget https://openssl.org/source/old/1.1.1/openssl-${OPENSSL_VERSION}.tar.gz -O openssl-${OPENSSL_VERSION}.tar.gz +tar -xzf openssl-${OPENSSL_VERSION}.tar.gz + +cd openssl-${OPENSSL_VERSION} +./config -no-shared -no-asm -no-zlib -no-comp -no-dgram -no-filenames -no-cms +make -j$(nproc || sysctl -n hw.ncpu || sysctl -n hw.logicalcpu) +cp -fr include ../../deps +cp libcrypto.a ../../deps/lib +cp libssl.a ../../deps/lib +cd .. diff --git a/scripts/build.openssl3.sh b/scripts/build.openssl3.sh new file mode 100755 index 00000000..4dd00382 --- /dev/null +++ b/scripts/build.openssl3.sh @@ -0,0 +1,20 @@ +#!/bin/sh -e + +OPENSSL_VERSION="3.0.16" + +mkdir -p deps +mkdir -p deps/include +mkdir -p deps/lib + +mkdir -p build && cd build + +wget https://github.com/openssl/openssl/releases/download/openssl-${OPENSSL_VERSION}/openssl-${OPENSSL_VERSION}.tar.gz -O openssl-${OPENSSL_VERSION}.tar.gz +tar -xzf openssl-${OPENSSL_VERSION}.tar.gz + +cd openssl-${OPENSSL_VERSION} +./config -no-shared -no-asm -no-zlib -no-comp -no-dgram -no-filenames -no-cms +make -j$(nproc || sysctl -n hw.ncpu || sysctl -n hw.logicalcpu) +cp -fr include ../../deps +cp libcrypto.a ../../deps/lib +cp libssl.a ../../deps/lib +cd .. diff --git a/scripts/build.uv.sh b/scripts/build.uv.sh new file mode 100755 index 00000000..47587cec --- /dev/null +++ b/scripts/build.uv.sh @@ -0,0 +1,20 @@ +#!/bin/sh -e + +UV_VERSION="1.51.0" + +mkdir -p deps +mkdir -p deps/include +mkdir -p deps/lib + +mkdir -p build && cd build + +wget https://dist.libuv.org/dist/v${UV_VERSION}/libuv-v${UV_VERSION}.tar.gz -O v${UV_VERSION}.tar.gz +tar -xzf v${UV_VERSION}.tar.gz + +cd libuv-v${UV_VERSION} +sh autogen.sh +./configure --disable-shared +make -j$(nproc || sysctl -n hw.ncpu || sysctl -n hw.logicalcpu) +cp -fr include ../../deps +cp .libs/libuv.a ../../deps/lib +cd .. diff --git a/scripts/build_deps.sh b/scripts/build_deps.sh index 7c4fc3da..d244665f 100755 --- a/scripts/build_deps.sh +++ b/scripts/build_deps.sh @@ -1,43 +1,5 @@ -#!/bin/bash -e +#!/bin/sh -e -UV_VERSION="1.34.0" -OPENSSL_VERSION="1.1.1d" -HWLOC_VERSION="2.1.0" - -mkdir deps -mkdir deps/include -mkdir deps/lib - -mkdir build && cd build - -wget https://github.com/libuv/libuv/archive/v${UV_VERSION}.tar.gz -tar -xzf v${UV_VERSION}.tar.gz - -wget https://download.open-mpi.org/release/hwloc/v2.1/hwloc-${HWLOC_VERSION}.tar.bz2 -tar -xjf hwloc-${HWLOC_VERSION}.tar.bz2 - -wget https://www.openssl.org/source/openssl-${OPENSSL_VERSION}.tar.gz -tar -xzf openssl-${OPENSSL_VERSION}.tar.gz - -cd libuv-${UV_VERSION} -sh autogen.sh -./configure --disable-shared -make -j$(nproc) -cp -fr include/ ../../deps -cp .libs/libuv.a ../../deps/lib -cd .. - -cd hwloc-${HWLOC_VERSION} -./configure --disable-shared --enable-static --disable-io --disable-libudev --disable-libxml2 -make -j$(nproc) -cp -fr include/ ../../deps -cp hwloc/.libs/libhwloc.a ../../deps/lib -cd .. - -cd openssl-${OPENSSL_VERSION} -./config -no-shared -no-asm -no-zlib -no-comp -no-dgram -no-filenames -no-cms -make -j$(nproc) -cp -fr include/ ../../deps -cp libcrypto.a ../../deps/lib -cp libssl.a ../../deps/lib -cd ../.. \ No newline at end of file +./build.uv.sh +./build.hwloc.sh +./build.openssl3.sh \ No newline at end of file diff --git a/scripts/enable_1gb_pages.sh b/scripts/enable_1gb_pages.sh index 16d889f1..a1fb4c61 100755 --- a/scripts/enable_1gb_pages.sh +++ b/scripts/enable_1gb_pages.sh @@ -1,4 +1,4 @@ -#!/bin/bash -e +#!/bin/sh -e # https://xmrig.com/docs/miner/hugepages#onegb-huge-pages diff --git a/scripts/generate_cl.js b/scripts/generate_cl.js index 19ed2380..287eefc7 100644 --- a/scripts/generate_cl.js +++ b/scripts/generate_cl.js @@ -6,7 +6,6 @@ const fs = require('fs'); const path = require('path'); const { text2h, text2h_bundle, addIncludes } = require('./js/opencl'); const { opencl_minify } = require('./js/opencl_minify'); -const cwd = process.cwd(); function cn() @@ -43,23 +42,14 @@ function cn_r() } -function cn_gpu() -{ - const cn_gpu = opencl_minify(addIncludes('cryptonight_gpu.cl', [ 'wolf-aes.cl', 'keccak.cl' ])); - - // fs.writeFileSync('cryptonight_gpu_gen.cl', cn_gpu); - fs.writeFileSync('cryptonight_gpu_cl.h', text2h(cn_gpu, 'xmrig', 'cryptonight_gpu_cl')); -} - - function rx() { let rx = addIncludes('randomx.cl', [ '../cn/algorithm.cl', 'randomx_constants_monero.h', 'randomx_constants_wow.h', - 'randomx_constants_loki.h', 'randomx_constants_arqma.h', + 'randomx_constants_graft.h', 'aes.cl', 'blake2b.cl', 'randomx_vm.cl', @@ -75,13 +65,34 @@ function rx() } -process.chdir(path.resolve('src/backend/opencl/cl/cn')); +function kawpow() +{ + const kawpow = opencl_minify(addIncludes('kawpow.cl', [ 'defs.h' ])); + const kawpow_dag = opencl_minify(addIncludes('kawpow_dag.cl', [ 'defs.h' ])); + // fs.writeFileSync('kawpow_gen.cl', kawpow); + fs.writeFileSync('kawpow_cl.h', text2h(kawpow, 'xmrig', 'kawpow_cl')); + fs.writeFileSync('kawpow_dag_cl.h', text2h(kawpow_dag, 'xmrig', 'kawpow_dag_cl')); +} + +for (let i = 0; i < 2; i++) { + if (fs.existsSync('src/backend/opencl/cl/OclSource.h')) { + break; + } + + process.chdir('..'); +} + +process.chdir(path.resolve('src/backend/opencl/cl')); + +const cwd = process.cwd(); + +process.chdir(path.resolve(cwd, 'cn')); cn(); cn_r(); -cn_gpu(); -process.chdir(cwd); -process.chdir(path.resolve('src/backend/opencl/cl/rx')); +process.chdir(path.resolve(cwd, 'rx')); +rx(); -rx(); \ No newline at end of file +process.chdir(path.resolve(cwd, 'kawpow')); +kawpow(); diff --git a/scripts/js/opencl.js b/scripts/js/opencl.js index 878aa44b..ec8c4454 100644 --- a/scripts/js/opencl.js +++ b/scripts/js/opencl.js @@ -6,7 +6,7 @@ const fs = require('fs'); function bin2h(buf, namespace, name) { const size = buf.byteLength; - let out = `#pragma once\n\nnamespace ${namespace} {\n\nstatic unsigned char ${name}[${size}] = {\n `; + let out = `#pragma once\n\nnamespace ${namespace} {\n\nstatic const unsigned char ${name}[${size}] = {\n `; let b = 32; for (let i = 0; i < size; i++) { @@ -28,7 +28,7 @@ function text2h_internal(text, name) { const buf = Buffer.from(text); const size = buf.byteLength; - let out = `\nstatic char ${name}[${size + 1}] = {\n `; + let out = `\nstatic const char ${name}[${size + 1}] = {\n `; let b = 32; for (let i = 0; i < size; i++) { diff --git a/scripts/pool_mine_example.cmd b/scripts/pool_mine_example.cmd new file mode 100644 index 00000000..38f93e2e --- /dev/null +++ b/scripts/pool_mine_example.cmd @@ -0,0 +1,20 @@ +:: Example batch file for mining Monero at a pool +:: +:: Format: +:: xmrig.exe -o : -u -p +:: +:: Fields: +:: pool address The host name of the pool stratum or its IP address, for example pool.hashvault.pro +:: pool port The port of the pool's stratum to connect to, for example 3333. Check your pool's getting started page. +:: pool username/wallet For most pools, this is the wallet address you want to mine to. Some pools require a username +:: pool password For most pools this can be just 'x'. For pools using usernames, you may need to provide a password as configured on the pool. +:: +:: List of Monero mining pools: +:: https://miningpoolstats.stream/monero +:: +:: Choose pools outside of top 5 to help Monero network be more decentralized! +:: Smaller pools also often have smaller fees/payout limits. + +cd /d "%~dp0" +xmrig.exe -o xmrpool.eu:3333 -u 48edfHu7V9Z84YzzMa6fUueoELZ9ZRXq9VetWzYGzKt52XU5xvqgzYnDK9URnRoJMk1j8nLwEVsaSWJ4fhdUyZijBGUicoD -p x +pause diff --git a/scripts/randomx_boost.sh b/scripts/randomx_boost.sh index ecbcdb4e..8580229a 100755 --- a/scripts/randomx_boost.sh +++ b/scripts/randomx_boost.sh @@ -1,18 +1,52 @@ -#!/bin/bash +#!/bin/sh -e -modprobe msr +MSR_FILE=/sys/module/msr/parameters/allow_writes -if cat /proc/cpuinfo | grep "AMD Ryzen" > /dev/null; +if test -e "$MSR_FILE"; then + echo on > $MSR_FILE +else + modprobe msr allow_writes=on +fi + +if grep -E 'AMD Ryzen|AMD EPYC|AuthenticAMD' /proc/cpuinfo > /dev/null; then - echo "Detected Ryzen" - wrmsr -a 0xc0011022 0x510000 - wrmsr -a 0xc001102b 0x1808cc16 - wrmsr -a 0xc0011020 0 - wrmsr -a 0xc0011021 0x40 - echo "MSR register values for Ryzen applied" -elif cat /proc/cpuinfo | grep "Intel" > /dev/null; + if grep "cpu family[[:space:]]\{1,\}:[[:space:]]25" /proc/cpuinfo > /dev/null; + then + if grep "model[[:space:]]\{1,\}:[[:space:]]97" /proc/cpuinfo > /dev/null; + then + echo "Detected Zen4 CPU" + wrmsr -a 0xc0011020 0x4400000000000 + wrmsr -a 0xc0011021 0x4000000000040 + wrmsr -a 0xc0011022 0x8680000401570000 + wrmsr -a 0xc001102b 0x2040cc10 + echo "MSR register values for Zen4 applied" + else + echo "Detected Zen3 CPU" + wrmsr -a 0xc0011020 0x4480000000000 + wrmsr -a 0xc0011021 0x1c000200000040 + wrmsr -a 0xc0011022 0xc000000401570000 + wrmsr -a 0xc001102b 0x2000cc10 + echo "MSR register values for Zen3 applied" + fi + elif grep "cpu family[[:space:]]\{1,\}:[[:space:]]26" /proc/cpuinfo > /dev/null; + then + echo "Detected Zen5 CPU" + wrmsr -a 0xc0011020 0x4400000000000 + wrmsr -a 0xc0011021 0x4000000000040 + wrmsr -a 0xc0011022 0x8680000401570000 + wrmsr -a 0xc001102b 0x2040cc10 + echo "MSR register values for Zen5 applied" + else + echo "Detected Zen1/Zen2 CPU" + wrmsr -a 0xc0011020 0 + wrmsr -a 0xc0011021 0x40 + wrmsr -a 0xc0011022 0x1510000 + wrmsr -a 0xc001102b 0x2000cc16 + echo "MSR register values for Zen1/Zen2 applied" + fi +elif grep "Intel" /proc/cpuinfo > /dev/null; then - echo "Detected Intel" + echo "Detected Intel CPU" wrmsr -a 0x1a4 0xf echo "MSR register values for Intel applied" else diff --git a/scripts/rtm_ghostrider_example.cmd b/scripts/rtm_ghostrider_example.cmd new file mode 100644 index 00000000..85e0a7fb --- /dev/null +++ b/scripts/rtm_ghostrider_example.cmd @@ -0,0 +1,23 @@ +:: Example batch file for mining Raptoreum at a pool +:: +:: Format: +:: xmrig.exe -a gr -o : -u -p +:: +:: Fields: +:: pool address The host name of the pool stratum or its IP address, for example raptoreumemporium.com +:: pool port The port of the pool's stratum to connect to, for example 3333. Check your pool's getting started page. +:: pool username/wallet For most pools, this is the wallet address you want to mine to. Some pools require a username +:: pool password For most pools this can be just 'x'. For pools using usernames, you may need to provide a password as configured on the pool. +:: +:: List of Raptoreum mining pools: +:: https://miningpoolstats.stream/raptoreum +:: +:: Choose pools outside of top 5 to help Raptoreum network be more decentralized! +:: Smaller pools also often have smaller fees/payout limits. + +cd /d "%~dp0" +:: Use this command line to connect to non-SSL port +xmrig.exe -a gr -o raptoreumemporium.com:3008 -u WALLET_ADDRESS -p x +:: Or use this command line to connect to an SSL port +:: xmrig.exe -a gr -o rtm.suprnova.cc:4273 --tls -u WALLET_ADDRESS -p x +pause diff --git a/scripts/solo_mine_example.cmd b/scripts/solo_mine_example.cmd new file mode 100644 index 00000000..ab912293 --- /dev/null +++ b/scripts/solo_mine_example.cmd @@ -0,0 +1,16 @@ +:: Example batch file for mining Monero solo +:: +:: Format: +:: xmrig.exe -o : -a rx/0 -u --daemon +:: +:: Fields: +:: node address The host name of your monerod node or its IP address. It can also be a public node with RPC enabled, for example node.xmr.to +:: node port The RPC port of your monerod node to connect to, usually 18081. +:: wallet address Check your Monero CLI or GUI wallet to see your wallet's address. +:: +:: Mining solo is the best way to help Monero network be more decentralized! +:: But you will only get a payout when you find a block which can take more than a year for a single low-end PC. + +cd /d "%~dp0" +xmrig.exe -o YOUR_NODE_IP:18081 -a rx/0 -u 48edfHu7V9Z84YzzMa6fUueoELZ9ZRXq9VetWzYGzKt52XU5xvqgzYnDK9URnRoJMk1j8nLwEVsaSWJ4fhdUyZijBGUicoD --daemon +pause diff --git a/src/3rdparty/CL/cl_dx9_media_sharing.h b/src/3rdparty/CL/cl_dx9_media_sharing.h index 2729e8b9..f60c0adc 100644 --- a/src/3rdparty/CL/cl_dx9_media_sharing.h +++ b/src/3rdparty/CL/cl_dx9_media_sharing.h @@ -44,7 +44,7 @@ extern "C" { typedef cl_uint cl_dx9_media_adapter_type_khr; typedef cl_uint cl_dx9_media_adapter_set_khr; - + #if defined(_WIN32) #include typedef struct _cl_dx9_surface_info_khr @@ -105,7 +105,7 @@ typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromDX9MediaSurfaceKHR_fn)( cl_mem_flags flags, cl_dx9_media_adapter_type_khr adapter_type, void * surface_info, - cl_uint plane, + cl_uint plane, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireDX9MediaSurfacesKHR_fn)( diff --git a/src/3rdparty/CL/cl_gl_ext.h b/src/3rdparty/CL/cl_gl_ext.h index c26d31ab..65ffc3f5 100644 --- a/src/3rdparty/CL/cl_gl_ext.h +++ b/src/3rdparty/CL/cl_gl_ext.h @@ -35,7 +35,7 @@ extern "C" { #include -/* +/* * cl_khr_gl_event extension */ #define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D diff --git a/src/3rdparty/adl/adl_defines.h b/src/3rdparty/adl/adl_defines.h new file mode 100644 index 00000000..f8350c41 --- /dev/null +++ b/src/3rdparty/adl/adl_defines.h @@ -0,0 +1,2342 @@ +// +// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. +// +// MIT LICENSE: +// 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. + +/// \file adl_defines.h +/// \brief Contains all definitions exposed by ADL for \ALL platforms.\n Included in ADL SDK +/// +/// This file contains all definitions used by ADL. +/// The ADL definitions include the following: +/// \li ADL error codes +/// \li Enumerations for the ADLDisplayInfo structure +/// \li Maximum limits +/// + +#ifndef ADL_DEFINES_H_ +#define ADL_DEFINES_H_ + +/// \defgroup DEFINES Constants and Definitions +// @{ + +/// \defgroup define_misc Miscellaneous Constant Definitions +// @{ + +/// \name General Definitions +// @{ + +/// Defines ADL_TRUE +#define ADL_TRUE 1 +/// Defines ADL_FALSE +#define ADL_FALSE 0 + +/// Defines the maximum string length +#define ADL_MAX_CHAR 4096 +/// Defines the maximum string length +#define ADL_MAX_PATH 256 +/// Defines the maximum number of supported adapters +#define ADL_MAX_ADAPTERS 250 +/// Defines the maxumum number of supported displays +#define ADL_MAX_DISPLAYS 150 +/// Defines the maxumum string length for device name +#define ADL_MAX_DEVICENAME 32 +/// Defines for all adapters +#define ADL_ADAPTER_INDEX_ALL -1 +/// Defines APIs with iOption none +#define ADL_MAIN_API_OPTION_NONE 0 +// @} + +/// \name Definitions for iOption parameter used by +/// ADL_Display_DDCBlockAccess_Get() +// @{ + +/// Switch to DDC line 2 before sending the command to the display. +#define ADL_DDC_OPTION_SWITCHDDC2 0x00000001 +/// Save command in the registry under a unique key, corresponding to parameter \b iCommandIndex +#define ADL_DDC_OPTION_RESTORECOMMAND 0x00000002 +/// Combine write-read DDC block access command. +#define ADL_DDC_OPTION_COMBOWRITEREAD 0x00000010 +/// Direct DDC access to the immediate device connected to graphics card. +/// MST with this option set: DDC command is sent to first branch. +/// MST with this option not set: DDC command is sent to the end node sink device. +#define ADL_DDC_OPTION_SENDTOIMMEDIATEDEVICE 0x00000020 +// @} + +/// \name Values for +/// ADLI2C.iAction used with ADL_Display_WriteAndReadI2C() +// @{ + +#define ADL_DL_I2C_ACTIONREAD 0x00000001 +#define ADL_DL_I2C_ACTIONWRITE 0x00000002 +#define ADL_DL_I2C_ACTIONREAD_REPEATEDSTART 0x00000003 +// @} + + +// @} //Misc + +/// \defgroup define_adl_results Result Codes +/// This group of definitions are the various results returned by all ADL functions \n +// @{ +/// All OK, but need to wait +#define ADL_OK_WAIT 4 +/// All OK, but need restart +#define ADL_OK_RESTART 3 +/// All OK but need mode change +#define ADL_OK_MODE_CHANGE 2 +/// All OK, but with warning +#define ADL_OK_WARNING 1 +/// ADL function completed successfully +#define ADL_OK 0 +/// Generic Error. Most likely one or more of the Escape calls to the driver failed! +#define ADL_ERR -1 +/// ADL not initialized +#define ADL_ERR_NOT_INIT -2 +/// One of the parameter passed is invalid +#define ADL_ERR_INVALID_PARAM -3 +/// One of the parameter size is invalid +#define ADL_ERR_INVALID_PARAM_SIZE -4 +/// Invalid ADL index passed +#define ADL_ERR_INVALID_ADL_IDX -5 +/// Invalid controller index passed +#define ADL_ERR_INVALID_CONTROLLER_IDX -6 +/// Invalid display index passed +#define ADL_ERR_INVALID_DIPLAY_IDX -7 +/// Function not supported by the driver +#define ADL_ERR_NOT_SUPPORTED -8 +/// Null Pointer error +#define ADL_ERR_NULL_POINTER -9 +/// Call can't be made due to disabled adapter +#define ADL_ERR_DISABLED_ADAPTER -10 +/// Invalid Callback +#define ADL_ERR_INVALID_CALLBACK -11 +/// Display Resource conflict +#define ADL_ERR_RESOURCE_CONFLICT -12 +//Failed to update some of the values. Can be returned by set request that include multiple values if not all values were successfully committed. +#define ADL_ERR_SET_INCOMPLETE -20 +/// There's no Linux XDisplay in Linux Console environment +#define ADL_ERR_NO_XDISPLAY -21 + +// @} +/// + +/// \defgroup define_display_type Display Type +/// Define Monitor/CRT display type +// @{ +/// Define Monitor display type +#define ADL_DT_MONITOR 0 +/// Define TV display type +#define ADL_DT_TELEVISION 1 +/// Define LCD display type +#define ADL_DT_LCD_PANEL 2 +/// Define DFP display type +#define ADL_DT_DIGITAL_FLAT_PANEL 3 +/// Define Componment Video display type +#define ADL_DT_COMPONENT_VIDEO 4 +/// Define Projector display type +#define ADL_DT_PROJECTOR 5 +// @} + +/// \defgroup define_display_connection_type Display Connection Type +// @{ +/// Define unknown display output type +#define ADL_DOT_UNKNOWN 0 +/// Define composite display output type +#define ADL_DOT_COMPOSITE 1 +/// Define SVideo display output type +#define ADL_DOT_SVIDEO 2 +/// Define analog display output type +#define ADL_DOT_ANALOG 3 +/// Define digital display output type +#define ADL_DOT_DIGITAL 4 +// @} + +/// \defgroup define_color_type Display Color Type and Source +/// Define Display Color Type and Source +// @{ +#define ADL_DISPLAY_COLOR_BRIGHTNESS (1 << 0) +#define ADL_DISPLAY_COLOR_CONTRAST (1 << 1) +#define ADL_DISPLAY_COLOR_SATURATION (1 << 2) +#define ADL_DISPLAY_COLOR_HUE (1 << 3) +#define ADL_DISPLAY_COLOR_TEMPERATURE (1 << 4) + +/// Color Temperature Source is EDID +#define ADL_DISPLAY_COLOR_TEMPERATURE_SOURCE_EDID (1 << 5) +/// Color Temperature Source is User +#define ADL_DISPLAY_COLOR_TEMPERATURE_SOURCE_USER (1 << 6) +// @} + +/// \defgroup define_adjustment_capabilities Display Adjustment Capabilities +/// Display adjustment capabilities values. Returned by ADL_Display_AdjustCaps_Get +// @{ +#define ADL_DISPLAY_ADJUST_OVERSCAN (1 << 0) +#define ADL_DISPLAY_ADJUST_VERT_POS (1 << 1) +#define ADL_DISPLAY_ADJUST_HOR_POS (1 << 2) +#define ADL_DISPLAY_ADJUST_VERT_SIZE (1 << 3) +#define ADL_DISPLAY_ADJUST_HOR_SIZE (1 << 4) +#define ADL_DISPLAY_ADJUST_SIZEPOS (ADL_DISPLAY_ADJUST_VERT_POS | ADL_DISPLAY_ADJUST_HOR_POS | ADL_DISPLAY_ADJUST_VERT_SIZE | ADL_DISPLAY_ADJUST_HOR_SIZE) +#define ADL_DISPLAY_CUSTOMMODES (1<<5) +#define ADL_DISPLAY_ADJUST_UNDERSCAN (1<<6) +// @} + +///Down-scale support +#define ADL_DISPLAY_CAPS_DOWNSCALE (1 << 0) + +/// Sharpness support +#define ADL_DISPLAY_CAPS_SHARPNESS (1 << 0) + +/// \defgroup define_desktop_config Desktop Configuration Flags +/// These flags are used by ADL_DesktopConfig_xxx +/// \deprecated This API has been deprecated because it was only used for RandR 1.1 (Red Hat 5.x) distributions which is now not supported. +// @{ +#define ADL_DESKTOPCONFIG_UNKNOWN 0 /* UNKNOWN desktop config */ +#define ADL_DESKTOPCONFIG_SINGLE (1 << 0) /* Single */ +#define ADL_DESKTOPCONFIG_CLONE (1 << 2) /* Clone */ +#define ADL_DESKTOPCONFIG_BIGDESK_H (1 << 4) /* Big Desktop Horizontal */ +#define ADL_DESKTOPCONFIG_BIGDESK_V (1 << 5) /* Big Desktop Vertical */ +#define ADL_DESKTOPCONFIG_BIGDESK_HR (1 << 6) /* Big Desktop Reverse Horz */ +#define ADL_DESKTOPCONFIG_BIGDESK_VR (1 << 7) /* Big Desktop Reverse Vert */ +#define ADL_DESKTOPCONFIG_RANDR12 (1 << 8) /* RandR 1.2 Multi-display */ +// @} + +/// needed for ADLDDCInfo structure +#define ADL_MAX_DISPLAY_NAME 256 + +/// \defgroup define_edid_flags Values for ulDDCInfoFlag +/// defines for ulDDCInfoFlag EDID flag +// @{ +#define ADL_DISPLAYDDCINFOEX_FLAG_PROJECTORDEVICE (1 << 0) +#define ADL_DISPLAYDDCINFOEX_FLAG_EDIDEXTENSION (1 << 1) +#define ADL_DISPLAYDDCINFOEX_FLAG_DIGITALDEVICE (1 << 2) +#define ADL_DISPLAYDDCINFOEX_FLAG_HDMIAUDIODEVICE (1 << 3) +#define ADL_DISPLAYDDCINFOEX_FLAG_SUPPORTS_AI (1 << 4) +#define ADL_DISPLAYDDCINFOEX_FLAG_SUPPORT_xvYCC601 (1 << 5) +#define ADL_DISPLAYDDCINFOEX_FLAG_SUPPORT_xvYCC709 (1 << 6) +// @} + +/// \defgroup define_displayinfo_connector Display Connector Type +/// defines for ADLDisplayInfo.iDisplayConnector +// @{ +#define ADL_DISPLAY_CONTYPE_UNKNOWN 0 +#define ADL_DISPLAY_CONTYPE_VGA 1 +#define ADL_DISPLAY_CONTYPE_DVI_D 2 +#define ADL_DISPLAY_CONTYPE_DVI_I 3 +#define ADL_DISPLAY_CONTYPE_ATICVDONGLE_NTSC 4 +#define ADL_DISPLAY_CONTYPE_ATICVDONGLE_JPN 5 +#define ADL_DISPLAY_CONTYPE_ATICVDONGLE_NONI2C_JPN 6 +#define ADL_DISPLAY_CONTYPE_ATICVDONGLE_NONI2C_NTSC 7 +#define ADL_DISPLAY_CONTYPE_PROPRIETARY 8 +#define ADL_DISPLAY_CONTYPE_HDMI_TYPE_A 10 +#define ADL_DISPLAY_CONTYPE_HDMI_TYPE_B 11 +#define ADL_DISPLAY_CONTYPE_SVIDEO 12 +#define ADL_DISPLAY_CONTYPE_COMPOSITE 13 +#define ADL_DISPLAY_CONTYPE_RCA_3COMPONENT 14 +#define ADL_DISPLAY_CONTYPE_DISPLAYPORT 15 +#define ADL_DISPLAY_CONTYPE_EDP 16 +#define ADL_DISPLAY_CONTYPE_WIRELESSDISPLAY 17 +// @} + +/// TV Capabilities and Standards +/// \defgroup define_tv_caps TV Capabilities and Standards +/// \deprecated Dropping support for TV displays +// @{ +#define ADL_TV_STANDARDS (1 << 0) +#define ADL_TV_SCART (1 << 1) + +/// TV Standards Definitions +#define ADL_STANDARD_NTSC_M (1 << 0) +#define ADL_STANDARD_NTSC_JPN (1 << 1) +#define ADL_STANDARD_NTSC_N (1 << 2) +#define ADL_STANDARD_PAL_B (1 << 3) +#define ADL_STANDARD_PAL_COMB_N (1 << 4) +#define ADL_STANDARD_PAL_D (1 << 5) +#define ADL_STANDARD_PAL_G (1 << 6) +#define ADL_STANDARD_PAL_H (1 << 7) +#define ADL_STANDARD_PAL_I (1 << 8) +#define ADL_STANDARD_PAL_K (1 << 9) +#define ADL_STANDARD_PAL_K1 (1 << 10) +#define ADL_STANDARD_PAL_L (1 << 11) +#define ADL_STANDARD_PAL_M (1 << 12) +#define ADL_STANDARD_PAL_N (1 << 13) +#define ADL_STANDARD_PAL_SECAM_D (1 << 14) +#define ADL_STANDARD_PAL_SECAM_K (1 << 15) +#define ADL_STANDARD_PAL_SECAM_K1 (1 << 16) +#define ADL_STANDARD_PAL_SECAM_L (1 << 17) +// @} + + +/// \defgroup define_video_custom_mode Video Custom Mode flags +/// Component Video Custom Mode flags. This is used by the iFlags parameter in ADLCustomMode +// @{ +#define ADL_CUSTOMIZEDMODEFLAG_MODESUPPORTED (1 << 0) +#define ADL_CUSTOMIZEDMODEFLAG_NOTDELETETABLE (1 << 1) +#define ADL_CUSTOMIZEDMODEFLAG_INSERTBYDRIVER (1 << 2) +#define ADL_CUSTOMIZEDMODEFLAG_INTERLACED (1 << 3) +#define ADL_CUSTOMIZEDMODEFLAG_BASEMODE (1 << 4) +// @} + +/// \defgroup define_ddcinfoflag Values used for DDCInfoFlag +/// ulDDCInfoFlag field values used by the ADLDDCInfo structure +// @{ +#define ADL_DISPLAYDDCINFOEX_FLAG_PROJECTORDEVICE (1 << 0) +#define ADL_DISPLAYDDCINFOEX_FLAG_EDIDEXTENSION (1 << 1) +#define ADL_DISPLAYDDCINFOEX_FLAG_DIGITALDEVICE (1 << 2) +#define ADL_DISPLAYDDCINFOEX_FLAG_HDMIAUDIODEVICE (1 << 3) +#define ADL_DISPLAYDDCINFOEX_FLAG_SUPPORTS_AI (1 << 4) +#define ADL_DISPLAYDDCINFOEX_FLAG_SUPPORT_xvYCC601 (1 << 5) +#define ADL_DISPLAYDDCINFOEX_FLAG_SUPPORT_xvYCC709 (1 << 6) +// @} + +/// \defgroup define_cv_dongle Values used by ADL_CV_DongleSettings_xxx +/// The following is applicable to ADL_DISPLAY_CONTYPE_ATICVDONGLE_JP and ADL_DISPLAY_CONTYPE_ATICVDONGLE_NONI2C_D only +/// \deprecated Dropping support for Component Video displays +// @{ +#define ADL_DISPLAY_CV_DONGLE_D1 (1 << 0) +#define ADL_DISPLAY_CV_DONGLE_D2 (1 << 1) +#define ADL_DISPLAY_CV_DONGLE_D3 (1 << 2) +#define ADL_DISPLAY_CV_DONGLE_D4 (1 << 3) +#define ADL_DISPLAY_CV_DONGLE_D5 (1 << 4) + +/// The following is applicable to ADL_DISPLAY_CONTYPE_ATICVDONGLE_NA and ADL_DISPLAY_CONTYPE_ATICVDONGLE_NONI2C only + +#define ADL_DISPLAY_CV_DONGLE_480I (1 << 0) +#define ADL_DISPLAY_CV_DONGLE_480P (1 << 1) +#define ADL_DISPLAY_CV_DONGLE_540P (1 << 2) +#define ADL_DISPLAY_CV_DONGLE_720P (1 << 3) +#define ADL_DISPLAY_CV_DONGLE_1080I (1 << 4) +#define ADL_DISPLAY_CV_DONGLE_1080P (1 << 5) +#define ADL_DISPLAY_CV_DONGLE_16_9 (1 << 6) +#define ADL_DISPLAY_CV_DONGLE_720P50 (1 << 7) +#define ADL_DISPLAY_CV_DONGLE_1080I25 (1 << 8) +#define ADL_DISPLAY_CV_DONGLE_576I25 (1 << 9) +#define ADL_DISPLAY_CV_DONGLE_576P50 (1 << 10) +#define ADL_DISPLAY_CV_DONGLE_1080P24 (1 << 11) +#define ADL_DISPLAY_CV_DONGLE_1080P25 (1 << 12) +#define ADL_DISPLAY_CV_DONGLE_1080P30 (1 << 13) +#define ADL_DISPLAY_CV_DONGLE_1080P50 (1 << 14) +// @} + +/// \defgroup define_formats_ovr Formats Override Settings +/// Display force modes flags +// @{ +/// +#define ADL_DISPLAY_FORMAT_FORCE_720P 0x00000001 +#define ADL_DISPLAY_FORMAT_FORCE_1080I 0x00000002 +#define ADL_DISPLAY_FORMAT_FORCE_1080P 0x00000004 +#define ADL_DISPLAY_FORMAT_FORCE_720P50 0x00000008 +#define ADL_DISPLAY_FORMAT_FORCE_1080I25 0x00000010 +#define ADL_DISPLAY_FORMAT_FORCE_576I25 0x00000020 +#define ADL_DISPLAY_FORMAT_FORCE_576P50 0x00000040 +#define ADL_DISPLAY_FORMAT_FORCE_1080P24 0x00000080 +#define ADL_DISPLAY_FORMAT_FORCE_1080P25 0x00000100 +#define ADL_DISPLAY_FORMAT_FORCE_1080P30 0x00000200 +#define ADL_DISPLAY_FORMAT_FORCE_1080P50 0x00000400 + +///< Below are \b EXTENDED display mode flags + +#define ADL_DISPLAY_FORMAT_CVDONGLEOVERIDE 0x00000001 +#define ADL_DISPLAY_FORMAT_CVMODEUNDERSCAN 0x00000002 +#define ADL_DISPLAY_FORMAT_FORCECONNECT_SUPPORTED 0x00000004 +#define ADL_DISPLAY_FORMAT_RESTRICT_FORMAT_SELECTION 0x00000008 +#define ADL_DISPLAY_FORMAT_SETASPECRATIO 0x00000010 +#define ADL_DISPLAY_FORMAT_FORCEMODES 0x00000020 +#define ADL_DISPLAY_FORMAT_LCDRTCCOEFF 0x00000040 +// @} + +/// Defines used by OD5 +#define ADL_PM_PARAM_DONT_CHANGE 0 + +/// The following defines Bus types +// @{ +#define ADL_BUSTYPE_PCI 0 /* PCI bus */ +#define ADL_BUSTYPE_AGP 1 /* AGP bus */ +#define ADL_BUSTYPE_PCIE 2 /* PCI Express bus */ +#define ADL_BUSTYPE_PCIE_GEN2 3 /* PCI Express 2nd generation bus */ +#define ADL_BUSTYPE_PCIE_GEN3 4 /* PCI Express 3rd generation bus */ +#define ADL_BUSTYPE_PCIE_GEN4 5 /* PCI Express 4th generation bus */ +// @} + +/// \defgroup define_ws_caps Workstation Capabilities +/// Workstation values +// @{ + +/// This value indicates that the workstation card supports active stereo though stereo output connector +#define ADL_STEREO_SUPPORTED (1 << 2) +/// This value indicates that the workstation card supports active stereo via "blue-line" +#define ADL_STEREO_BLUE_LINE (1 << 3) +/// This value is used to turn off stereo mode. +#define ADL_STEREO_OFF 0 +/// This value indicates that the workstation card supports active stereo. This is also used to set the stereo mode to active though the stereo output connector +#define ADL_STEREO_ACTIVE (1 << 1) +/// This value indicates that the workstation card supports auto-stereo monitors with horizontal interleave. This is also used to set the stereo mode to use the auto-stereo monitor with horizontal interleave +#define ADL_STEREO_AUTO_HORIZONTAL (1 << 30) +/// This value indicates that the workstation card supports auto-stereo monitors with vertical interleave. This is also used to set the stereo mode to use the auto-stereo monitor with vertical interleave +#define ADL_STEREO_AUTO_VERTICAL (1 << 31) +/// This value indicates that the workstation card supports passive stereo, ie. non stereo sync +#define ADL_STEREO_PASSIVE (1 << 6) +/// This value indicates that the workstation card supports auto-stereo monitors with vertical interleave. This is also used to set the stereo mode to use the auto-stereo monitor with vertical interleave +#define ADL_STEREO_PASSIVE_HORIZ (1 << 7) +/// This value indicates that the workstation card supports auto-stereo monitors with vertical interleave. This is also used to set the stereo mode to use the auto-stereo monitor with vertical interleave +#define ADL_STEREO_PASSIVE_VERT (1 << 8) +/// This value indicates that the workstation card supports auto-stereo monitors with Samsung. +#define ADL_STEREO_AUTO_SAMSUNG (1 << 11) +/// This value indicates that the workstation card supports auto-stereo monitors with Tridility. +#define ADL_STEREO_AUTO_TSL (1 << 12) +/// This value indicates that the workstation card supports DeepBitDepth (10 bpp) +#define ADL_DEEPBITDEPTH_10BPP_SUPPORTED (1 << 5) + +/// This value indicates that the workstation supports 8-Bit Grayscale +#define ADL_8BIT_GREYSCALE_SUPPORTED (1 << 9) +/// This value indicates that the workstation supports CUSTOM TIMING +#define ADL_CUSTOM_TIMING_SUPPORTED (1 << 10) + +/// Load balancing is supported. +#define ADL_WORKSTATION_LOADBALANCING_SUPPORTED 0x00000001 +/// Load balancing is available. +#define ADL_WORKSTATION_LOADBALANCING_AVAILABLE 0x00000002 + +/// Load balancing is disabled. +#define ADL_WORKSTATION_LOADBALANCING_DISABLED 0x00000000 +/// Load balancing is Enabled. +#define ADL_WORKSTATION_LOADBALANCING_ENABLED 0x00000001 + + + +// @} + +/// \defgroup define_adapterspeed speed setting from the adapter +// @{ +#define ADL_CONTEXT_SPEED_UNFORCED 0 /* default asic running speed */ +#define ADL_CONTEXT_SPEED_FORCEHIGH 1 /* asic running speed is forced to high */ +#define ADL_CONTEXT_SPEED_FORCELOW 2 /* asic running speed is forced to low */ + +#define ADL_ADAPTER_SPEEDCAPS_SUPPORTED (1 << 0) /* change asic running speed setting is supported */ +// @} + +/// \defgroup define_glsync Genlock related values +/// GL-Sync port types (unique values) +// @{ +/// Unknown port of GL-Sync module +#define ADL_GLSYNC_PORT_UNKNOWN 0 +/// BNC port of of GL-Sync module +#define ADL_GLSYNC_PORT_BNC 1 +/// RJ45(1) port of of GL-Sync module +#define ADL_GLSYNC_PORT_RJ45PORT1 2 +/// RJ45(2) port of of GL-Sync module +#define ADL_GLSYNC_PORT_RJ45PORT2 3 + +// GL-Sync Genlock settings mask (bit-vector) + +/// None of the ADLGLSyncGenlockConfig members are valid +#define ADL_GLSYNC_CONFIGMASK_NONE 0 +/// The ADLGLSyncGenlockConfig.lSignalSource member is valid +#define ADL_GLSYNC_CONFIGMASK_SIGNALSOURCE (1 << 0) +/// The ADLGLSyncGenlockConfig.iSyncField member is valid +#define ADL_GLSYNC_CONFIGMASK_SYNCFIELD (1 << 1) +/// The ADLGLSyncGenlockConfig.iSampleRate member is valid +#define ADL_GLSYNC_CONFIGMASK_SAMPLERATE (1 << 2) +/// The ADLGLSyncGenlockConfig.lSyncDelay member is valid +#define ADL_GLSYNC_CONFIGMASK_SYNCDELAY (1 << 3) +/// The ADLGLSyncGenlockConfig.iTriggerEdge member is valid +#define ADL_GLSYNC_CONFIGMASK_TRIGGEREDGE (1 << 4) +/// The ADLGLSyncGenlockConfig.iScanRateCoeff member is valid +#define ADL_GLSYNC_CONFIGMASK_SCANRATECOEFF (1 << 5) +/// The ADLGLSyncGenlockConfig.lFramelockCntlVector member is valid +#define ADL_GLSYNC_CONFIGMASK_FRAMELOCKCNTL (1 << 6) + + +// GL-Sync Framelock control mask (bit-vector) + +/// Framelock is disabled +#define ADL_GLSYNC_FRAMELOCKCNTL_NONE 0 +/// Framelock is enabled +#define ADL_GLSYNC_FRAMELOCKCNTL_ENABLE ( 1 << 0) + +#define ADL_GLSYNC_FRAMELOCKCNTL_DISABLE ( 1 << 1) +#define ADL_GLSYNC_FRAMELOCKCNTL_SWAP_COUNTER_RESET ( 1 << 2) +#define ADL_GLSYNC_FRAMELOCKCNTL_SWAP_COUNTER_ACK ( 1 << 3) +#define ADL_GLSYNC_FRAMELOCKCNTL_VERSION_KMD (1 << 4) + +#define ADL_GLSYNC_FRAMELOCKCNTL_STATE_ENABLE ( 1 << 0) +#define ADL_GLSYNC_FRAMELOCKCNTL_STATE_KMD (1 << 4) + +// GL-Sync Framelock counters mask (bit-vector) +#define ADL_GLSYNC_COUNTER_SWAP ( 1 << 0 ) + +// GL-Sync Signal Sources (unique values) + +/// GL-Sync signal source is undefined +#define ADL_GLSYNC_SIGNALSOURCE_UNDEFINED 0x00000100 +/// GL-Sync signal source is Free Run +#define ADL_GLSYNC_SIGNALSOURCE_FREERUN 0x00000101 +/// GL-Sync signal source is the BNC GL-Sync port +#define ADL_GLSYNC_SIGNALSOURCE_BNCPORT 0x00000102 +/// GL-Sync signal source is the RJ45(1) GL-Sync port +#define ADL_GLSYNC_SIGNALSOURCE_RJ45PORT1 0x00000103 +/// GL-Sync signal source is the RJ45(2) GL-Sync port +#define ADL_GLSYNC_SIGNALSOURCE_RJ45PORT2 0x00000104 + + +// GL-Sync Signal Types (unique values) + +/// GL-Sync signal type is unknown +#define ADL_GLSYNC_SIGNALTYPE_UNDEFINED 0 +/// GL-Sync signal type is 480I +#define ADL_GLSYNC_SIGNALTYPE_480I 1 +/// GL-Sync signal type is 576I +#define ADL_GLSYNC_SIGNALTYPE_576I 2 +/// GL-Sync signal type is 480P +#define ADL_GLSYNC_SIGNALTYPE_480P 3 +/// GL-Sync signal type is 576P +#define ADL_GLSYNC_SIGNALTYPE_576P 4 +/// GL-Sync signal type is 720P +#define ADL_GLSYNC_SIGNALTYPE_720P 5 +/// GL-Sync signal type is 1080P +#define ADL_GLSYNC_SIGNALTYPE_1080P 6 +/// GL-Sync signal type is 1080I +#define ADL_GLSYNC_SIGNALTYPE_1080I 7 +/// GL-Sync signal type is SDI +#define ADL_GLSYNC_SIGNALTYPE_SDI 8 +/// GL-Sync signal type is TTL +#define ADL_GLSYNC_SIGNALTYPE_TTL 9 +/// GL_Sync signal type is Analog +#define ADL_GLSYNC_SIGNALTYPE_ANALOG 10 + +// GL-Sync Sync Field options (unique values) + +///GL-Sync sync field option is undefined +#define ADL_GLSYNC_SYNCFIELD_UNDEFINED 0 +///GL-Sync sync field option is Sync to Field 1 (used for Interlaced signal types) +#define ADL_GLSYNC_SYNCFIELD_BOTH 1 +///GL-Sync sync field option is Sync to Both fields (used for Interlaced signal types) +#define ADL_GLSYNC_SYNCFIELD_1 2 + + +// GL-Sync trigger edge options (unique values) + +/// GL-Sync trigger edge is undefined +#define ADL_GLSYNC_TRIGGEREDGE_UNDEFINED 0 +/// GL-Sync trigger edge is the rising edge +#define ADL_GLSYNC_TRIGGEREDGE_RISING 1 +/// GL-Sync trigger edge is the falling edge +#define ADL_GLSYNC_TRIGGEREDGE_FALLING 2 +/// GL-Sync trigger edge is both the rising and the falling edge +#define ADL_GLSYNC_TRIGGEREDGE_BOTH 3 + + +// GL-Sync scan rate coefficient/multiplier options (unique values) + +/// GL-Sync scan rate coefficient/multiplier is undefined +#define ADL_GLSYNC_SCANRATECOEFF_UNDEFINED 0 +/// GL-Sync scan rate coefficient/multiplier is 5 +#define ADL_GLSYNC_SCANRATECOEFF_x5 1 +/// GL-Sync scan rate coefficient/multiplier is 4 +#define ADL_GLSYNC_SCANRATECOEFF_x4 2 +/// GL-Sync scan rate coefficient/multiplier is 3 +#define ADL_GLSYNC_SCANRATECOEFF_x3 3 +/// GL-Sync scan rate coefficient/multiplier is 5:2 (SMPTE) +#define ADL_GLSYNC_SCANRATECOEFF_x5_DIV_2 4 +/// GL-Sync scan rate coefficient/multiplier is 2 +#define ADL_GLSYNC_SCANRATECOEFF_x2 5 +/// GL-Sync scan rate coefficient/multiplier is 3 : 2 +#define ADL_GLSYNC_SCANRATECOEFF_x3_DIV_2 6 +/// GL-Sync scan rate coefficient/multiplier is 5 : 4 +#define ADL_GLSYNC_SCANRATECOEFF_x5_DIV_4 7 +/// GL-Sync scan rate coefficient/multiplier is 1 (default) +#define ADL_GLSYNC_SCANRATECOEFF_x1 8 +/// GL-Sync scan rate coefficient/multiplier is 4 : 5 +#define ADL_GLSYNC_SCANRATECOEFF_x4_DIV_5 9 +/// GL-Sync scan rate coefficient/multiplier is 2 : 3 +#define ADL_GLSYNC_SCANRATECOEFF_x2_DIV_3 10 +/// GL-Sync scan rate coefficient/multiplier is 1 : 2 +#define ADL_GLSYNC_SCANRATECOEFF_x1_DIV_2 11 +/// GL-Sync scan rate coefficient/multiplier is 2 : 5 (SMPTE) +#define ADL_GLSYNC_SCANRATECOEFF_x2_DIV_5 12 +/// GL-Sync scan rate coefficient/multiplier is 1 : 3 +#define ADL_GLSYNC_SCANRATECOEFF_x1_DIV_3 13 +/// GL-Sync scan rate coefficient/multiplier is 1 : 4 +#define ADL_GLSYNC_SCANRATECOEFF_x1_DIV_4 14 +/// GL-Sync scan rate coefficient/multiplier is 1 : 5 +#define ADL_GLSYNC_SCANRATECOEFF_x1_DIV_5 15 + + +// GL-Sync port (signal presence) states (unique values) + +/// GL-Sync port state is undefined +#define ADL_GLSYNC_PORTSTATE_UNDEFINED 0 +/// GL-Sync port is not connected +#define ADL_GLSYNC_PORTSTATE_NOCABLE 1 +/// GL-Sync port is Idle +#define ADL_GLSYNC_PORTSTATE_IDLE 2 +/// GL-Sync port has an Input signal +#define ADL_GLSYNC_PORTSTATE_INPUT 3 +/// GL-Sync port is Output +#define ADL_GLSYNC_PORTSTATE_OUTPUT 4 + + +// GL-Sync LED types (used index within ADL_Workstation_GLSyncPortState_Get returned ppGlSyncLEDs array) (unique values) + +/// Index into the ADL_Workstation_GLSyncPortState_Get returned ppGlSyncLEDs array for the one LED of the BNC port +#define ADL_GLSYNC_LEDTYPE_BNC 0 +/// Index into the ADL_Workstation_GLSyncPortState_Get returned ppGlSyncLEDs array for the Left LED of the RJ45(1) or RJ45(2) port +#define ADL_GLSYNC_LEDTYPE_RJ45_LEFT 0 +/// Index into the ADL_Workstation_GLSyncPortState_Get returned ppGlSyncLEDs array for the Right LED of the RJ45(1) or RJ45(2) port +#define ADL_GLSYNC_LEDTYPE_RJ45_RIGHT 1 + + +// GL-Sync LED colors (unique values) + +/// GL-Sync LED undefined color +#define ADL_GLSYNC_LEDCOLOR_UNDEFINED 0 +/// GL-Sync LED is unlit +#define ADL_GLSYNC_LEDCOLOR_NOLIGHT 1 +/// GL-Sync LED is yellow +#define ADL_GLSYNC_LEDCOLOR_YELLOW 2 +/// GL-Sync LED is red +#define ADL_GLSYNC_LEDCOLOR_RED 3 +/// GL-Sync LED is green +#define ADL_GLSYNC_LEDCOLOR_GREEN 4 +/// GL-Sync LED is flashing green +#define ADL_GLSYNC_LEDCOLOR_FLASH_GREEN 5 + + +// GL-Sync Port Control (refers one GL-Sync Port) (unique values) + +/// Used to configure the RJ54(1) or RJ42(2) port of GL-Sync is as Idle +#define ADL_GLSYNC_PORTCNTL_NONE 0x00000000 +/// Used to configure the RJ54(1) or RJ42(2) port of GL-Sync is as Output +#define ADL_GLSYNC_PORTCNTL_OUTPUT 0x00000001 + + +// GL-Sync Mode Control (refers one Display/Controller) (bitfields) + +/// Used to configure the display to use internal timing (not genlocked) +#define ADL_GLSYNC_MODECNTL_NONE 0x00000000 +/// Bitfield used to configure the display as genlocked (either as Timing Client or as Timing Server) +#define ADL_GLSYNC_MODECNTL_GENLOCK 0x00000001 +/// Bitfield used to configure the display as Timing Server +#define ADL_GLSYNC_MODECNTL_TIMINGSERVER 0x00000002 + +// GL-Sync Mode Status +/// Display is currently not genlocked +#define ADL_GLSYNC_MODECNTL_STATUS_NONE 0x00000000 +/// Display is currently genlocked +#define ADL_GLSYNC_MODECNTL_STATUS_GENLOCK 0x00000001 +/// Display requires a mode switch +#define ADL_GLSYNC_MODECNTL_STATUS_SETMODE_REQUIRED 0x00000002 +/// Display is capable of being genlocked +#define ADL_GLSYNC_MODECNTL_STATUS_GENLOCK_ALLOWED 0x00000004 + +#define ADL_MAX_GLSYNC_PORTS 8 +#define ADL_MAX_GLSYNC_PORT_LEDS 8 + +// @} + +/// \defgroup define_crossfirestate CrossfireX state of a particular adapter CrossfireX combination +// @{ +#define ADL_XFIREX_STATE_NOINTERCONNECT ( 1 << 0 ) /* Dongle / cable is missing */ +#define ADL_XFIREX_STATE_DOWNGRADEPIPES ( 1 << 1 ) /* CrossfireX can be enabled if pipes are downgraded */ +#define ADL_XFIREX_STATE_DOWNGRADEMEM ( 1 << 2 ) /* CrossfireX cannot be enabled unless mem downgraded */ +#define ADL_XFIREX_STATE_REVERSERECOMMENDED ( 1 << 3 ) /* Card reversal recommended, CrossfireX cannot be enabled. */ +#define ADL_XFIREX_STATE_3DACTIVE ( 1 << 4 ) /* 3D client is active - CrossfireX cannot be safely enabled */ +#define ADL_XFIREX_STATE_MASTERONSLAVE ( 1 << 5 ) /* Dongle is OK but master is on slave */ +#define ADL_XFIREX_STATE_NODISPLAYCONNECT ( 1 << 6 ) /* No (valid) display connected to master card. */ +#define ADL_XFIREX_STATE_NOPRIMARYVIEW ( 1 << 7 ) /* CrossfireX is enabled but master is not current primary device */ +#define ADL_XFIREX_STATE_DOWNGRADEVISMEM ( 1 << 8 ) /* CrossfireX cannot be enabled unless visible mem downgraded */ +#define ADL_XFIREX_STATE_LESSTHAN8LANE_MASTER ( 1 << 9 ) /* CrossfireX can be enabled however performance not optimal due to <8 lanes */ +#define ADL_XFIREX_STATE_LESSTHAN8LANE_SLAVE ( 1 << 10 ) /* CrossfireX can be enabled however performance not optimal due to <8 lanes */ +#define ADL_XFIREX_STATE_PEERTOPEERFAILED ( 1 << 11 ) /* CrossfireX cannot be enabled due to failed peer to peer test */ +#define ADL_XFIREX_STATE_MEMISDOWNGRADED ( 1 << 16 ) /* Notification that memory is currently downgraded */ +#define ADL_XFIREX_STATE_PIPESDOWNGRADED ( 1 << 17 ) /* Notification that pipes are currently downgraded */ +#define ADL_XFIREX_STATE_XFIREXACTIVE ( 1 << 18 ) /* CrossfireX is enabled on current device */ +#define ADL_XFIREX_STATE_VISMEMISDOWNGRADED ( 1 << 19 ) /* Notification that visible FB memory is currently downgraded */ +#define ADL_XFIREX_STATE_INVALIDINTERCONNECTION ( 1 << 20 ) /* Cannot support current inter-connection configuration */ +#define ADL_XFIREX_STATE_NONP2PMODE ( 1 << 21 ) /* CrossfireX will only work with clients supporting non P2P mode */ +#define ADL_XFIREX_STATE_DOWNGRADEMEMBANKS ( 1 << 22 ) /* CrossfireX cannot be enabled unless memory banks downgraded */ +#define ADL_XFIREX_STATE_MEMBANKSDOWNGRADED ( 1 << 23 ) /* Notification that memory banks are currently downgraded */ +#define ADL_XFIREX_STATE_DUALDISPLAYSALLOWED ( 1 << 24 ) /* Extended desktop or clone mode is allowed. */ +#define ADL_XFIREX_STATE_P2P_APERTURE_MAPPING ( 1 << 25 ) /* P2P mapping was through peer aperture */ +#define ADL_XFIREX_STATE_P2PFLUSH_REQUIRED ADL_XFIREX_STATE_P2P_APERTURE_MAPPING /* For back compatible */ +#define ADL_XFIREX_STATE_XSP_CONNECTED ( 1 << 26 ) /* There is CrossfireX side port connection between GPUs */ +#define ADL_XFIREX_STATE_ENABLE_CF_REBOOT_REQUIRED ( 1 << 27 ) /* System needs a reboot bofore enable CrossfireX */ +#define ADL_XFIREX_STATE_DISABLE_CF_REBOOT_REQUIRED ( 1 << 28 ) /* System needs a reboot after disable CrossfireX */ +#define ADL_XFIREX_STATE_DRV_HANDLE_DOWNGRADE_KEY ( 1 << 29 ) /* Indicate base driver handles the downgrade key updating */ +#define ADL_XFIREX_STATE_CF_RECONFIG_REQUIRED ( 1 << 30 ) /* CrossfireX need to be reconfigured by CCC because of a LDA chain broken */ +#define ADL_XFIREX_STATE_ERRORGETTINGSTATUS ( 1 << 31 ) /* Could not obtain current status */ +// @} + +/////////////////////////////////////////////////////////////////////////// +// ADL_DISPLAY_ADJUSTMENT_PIXELFORMAT adjustment values +// (bit-vector) +/////////////////////////////////////////////////////////////////////////// +/// \defgroup define_pixel_formats Pixel Formats values +/// This group defines the various Pixel Formats that a particular digital display can support. \n +/// Since a display can support multiple formats, these values can be bit-or'ed to indicate the various formats \n +// @{ +#define ADL_DISPLAY_PIXELFORMAT_UNKNOWN 0 +#define ADL_DISPLAY_PIXELFORMAT_RGB (1 << 0) +#define ADL_DISPLAY_PIXELFORMAT_YCRCB444 (1 << 1) //Limited range +#define ADL_DISPLAY_PIXELFORMAT_YCRCB422 (1 << 2) //Limited range +#define ADL_DISPLAY_PIXELFORMAT_RGB_LIMITED_RANGE (1 << 3) +#define ADL_DISPLAY_PIXELFORMAT_RGB_FULL_RANGE ADL_DISPLAY_PIXELFORMAT_RGB //Full range +#define ADL_DISPLAY_PIXELFORMAT_YCRCB420 (1 << 4) +// @} + +/// \defgroup define_contype Connector Type Values +/// ADLDisplayConfig.ulConnectorType defines +// @{ +#define ADL_DL_DISPLAYCONFIG_CONTYPE_UNKNOWN 0 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_CV_NONI2C_JP 1 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_CV_JPN 2 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_CV_NA 3 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_CV_NONI2C_NA 4 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_VGA 5 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_DVI_D 6 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_DVI_I 7 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_HDMI_TYPE_A 8 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_HDMI_TYPE_B 9 +#define ADL_DL_DISPLAYCONFIG_CONTYPE_DISPLAYPORT 10 +// @} + +/////////////////////////////////////////////////////////////////////////// +// ADL_DISPLAY_DISPLAYINFO_ Definitions +// for ADLDisplayInfo.iDisplayInfoMask and ADLDisplayInfo.iDisplayInfoValue +// (bit-vector) +/////////////////////////////////////////////////////////////////////////// +/// \defgroup define_displayinfomask Display Info Mask Values +// @{ +#define ADL_DISPLAY_DISPLAYINFO_DISPLAYCONNECTED 0x00000001 +#define ADL_DISPLAY_DISPLAYINFO_DISPLAYMAPPED 0x00000002 +#define ADL_DISPLAY_DISPLAYINFO_NONLOCAL 0x00000004 +#define ADL_DISPLAY_DISPLAYINFO_FORCIBLESUPPORTED 0x00000008 +#define ADL_DISPLAY_DISPLAYINFO_GENLOCKSUPPORTED 0x00000010 +#define ADL_DISPLAY_DISPLAYINFO_MULTIVPU_SUPPORTED 0x00000020 +#define ADL_DISPLAY_DISPLAYINFO_LDA_DISPLAY 0x00000040 +#define ADL_DISPLAY_DISPLAYINFO_MODETIMING_OVERRIDESSUPPORTED 0x00000080 + +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_SINGLE 0x00000100 +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_CLONE 0x00000200 + +/// Legacy support for XP +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_2VSTRETCH 0x00000400 +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_2HSTRETCH 0x00000800 +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_EXTENDED 0x00001000 + +/// More support manners +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_NSTRETCH1GPU 0x00010000 +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_NSTRETCHNGPU 0x00020000 +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_RESERVED2 0x00040000 +#define ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_RESERVED3 0x00080000 + +/// Projector display type +#define ADL_DISPLAY_DISPLAYINFO_SHOWTYPE_PROJECTOR 0x00100000 + +// @} + + +/////////////////////////////////////////////////////////////////////////// +// ADL_ADAPTER_DISPLAY_MANNER_SUPPORTED_ Definitions +// for ADLAdapterDisplayCap of ADL_Adapter_Display_Cap() +// (bit-vector) +/////////////////////////////////////////////////////////////////////////// +/// \defgroup define_adaptermanner Adapter Manner Support Values +// @{ +#define ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_NOTACTIVE 0x00000001 +#define ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_SINGLE 0x00000002 +#define ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_CLONE 0x00000004 +#define ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_NSTRETCH1GPU 0x00000008 +#define ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_NSTRETCHNGPU 0x00000010 + +/// Legacy support for XP +#define ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_2VSTRETCH 0x00000020 +#define ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_2HSTRETCH 0x00000040 +#define ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_EXTENDED 0x00000080 + +#define ADL_ADAPTER_DISPLAYCAP_PREFERDISPLAY_SUPPORTED 0x00000100 +#define ADL_ADAPTER_DISPLAYCAP_BEZEL_SUPPORTED 0x00000200 + + +/////////////////////////////////////////////////////////////////////////// +// ADL_DISPLAY_DISPLAYMAP_MANNER_ Definitions +// for ADLDisplayMap.iDisplayMapMask and ADLDisplayMap.iDisplayMapValue +// (bit-vector) +/////////////////////////////////////////////////////////////////////////// +#define ADL_DISPLAY_DISPLAYMAP_MANNER_RESERVED 0x00000001 +#define ADL_DISPLAY_DISPLAYMAP_MANNER_NOTACTIVE 0x00000002 +#define ADL_DISPLAY_DISPLAYMAP_MANNER_SINGLE 0x00000004 +#define ADL_DISPLAY_DISPLAYMAP_MANNER_CLONE 0x00000008 +#define ADL_DISPLAY_DISPLAYMAP_MANNER_RESERVED1 0x00000010 // Removed NSTRETCH +#define ADL_DISPLAY_DISPLAYMAP_MANNER_HSTRETCH 0x00000020 +#define ADL_DISPLAY_DISPLAYMAP_MANNER_VSTRETCH 0x00000040 +#define ADL_DISPLAY_DISPLAYMAP_MANNER_VLD 0x00000080 + +// @} + +/////////////////////////////////////////////////////////////////////////// +// ADL_DISPLAY_DISPLAYMAP_OPTION_ Definitions +// for iOption in function ADL_Display_DisplayMapConfig_Get +// (bit-vector) +/////////////////////////////////////////////////////////////////////////// +#define ADL_DISPLAY_DISPLAYMAP_OPTION_GPUINFO 0x00000001 + +/////////////////////////////////////////////////////////////////////////// +// ADL_DISPLAY_DISPLAYTARGET_ Definitions +// for ADLDisplayTarget.iDisplayTargetMask and ADLDisplayTarget.iDisplayTargetValue +// (bit-vector) +/////////////////////////////////////////////////////////////////////////// +#define ADL_DISPLAY_DISPLAYTARGET_PREFERRED 0x00000001 + +/////////////////////////////////////////////////////////////////////////// +// ADL_DISPLAY_POSSIBLEMAPRESULT_VALID Definitions +// for ADLPossibleMapResult.iPossibleMapResultMask and ADLPossibleMapResult.iPossibleMapResultValue +// (bit-vector) +/////////////////////////////////////////////////////////////////////////// +#define ADL_DISPLAY_POSSIBLEMAPRESULT_VALID 0x00000001 +#define ADL_DISPLAY_POSSIBLEMAPRESULT_BEZELSUPPORTED 0x00000002 +#define ADL_DISPLAY_POSSIBLEMAPRESULT_OVERLAPSUPPORTED 0x00000004 + +/////////////////////////////////////////////////////////////////////////// +// ADL_DISPLAY_MODE_ Definitions +// for ADLMode.iModeMask, ADLMode.iModeValue, and ADLMode.iModeFlag +// (bit-vector) +/////////////////////////////////////////////////////////////////////////// +/// \defgroup define_displaymode Display Mode Values +// @{ +#define ADL_DISPLAY_MODE_COLOURFORMAT_565 0x00000001 +#define ADL_DISPLAY_MODE_COLOURFORMAT_8888 0x00000002 +#define ADL_DISPLAY_MODE_ORIENTATION_SUPPORTED_000 0x00000004 +#define ADL_DISPLAY_MODE_ORIENTATION_SUPPORTED_090 0x00000008 +#define ADL_DISPLAY_MODE_ORIENTATION_SUPPORTED_180 0x00000010 +#define ADL_DISPLAY_MODE_ORIENTATION_SUPPORTED_270 0x00000020 +#define ADL_DISPLAY_MODE_REFRESHRATE_ROUNDED 0x00000040 +#define ADL_DISPLAY_MODE_REFRESHRATE_ONLY 0x00000080 + +#define ADL_DISPLAY_MODE_PROGRESSIVE_FLAG 0 +#define ADL_DISPLAY_MODE_INTERLACED_FLAG 2 +// @} + +/////////////////////////////////////////////////////////////////////////// +// ADL_OSMODEINFO Definitions +/////////////////////////////////////////////////////////////////////////// +/// \defgroup define_osmode OS Mode Values +// @{ +#define ADL_OSMODEINFOXPOS_DEFAULT -640 +#define ADL_OSMODEINFOYPOS_DEFAULT 0 +#define ADL_OSMODEINFOXRES_DEFAULT 640 +#define ADL_OSMODEINFOYRES_DEFAULT 480 +#define ADL_OSMODEINFOXRES_DEFAULT800 800 +#define ADL_OSMODEINFOYRES_DEFAULT600 600 +#define ADL_OSMODEINFOREFRESHRATE_DEFAULT 60 +#define ADL_OSMODEINFOCOLOURDEPTH_DEFAULT 8 +#define ADL_OSMODEINFOCOLOURDEPTH_DEFAULT16 16 +#define ADL_OSMODEINFOCOLOURDEPTH_DEFAULT24 24 +#define ADL_OSMODEINFOCOLOURDEPTH_DEFAULT32 32 +#define ADL_OSMODEINFOORIENTATION_DEFAULT 0 +#define ADL_OSMODEINFOORIENTATION_DEFAULT_WIN7 DISPLAYCONFIG_ROTATION_FORCE_UINT32 +#define ADL_OSMODEFLAG_DEFAULT 0 +// @} + + +/////////////////////////////////////////////////////////////////////////// +// ADLThreadingModel Enumeration +/////////////////////////////////////////////////////////////////////////// +/// \defgroup thread_model +/// Used with \ref ADL_Main_ControlX2_Create and \ref ADL2_Main_ControlX2_Create to specify how ADL handles API calls when executed by multiple threads concurrently. +/// \brief Declares ADL threading behavior. +// @{ +typedef enum ADLThreadingModel +{ + ADL_THREADING_UNLOCKED = 0, /*!< Default behavior. ADL will not enforce serialization of ADL API executions by multiple threads. Multiple threads will be allowed to enter to ADL at the same time. Note that ADL library is not guaranteed to be thread-safe. Client that calls ADL_Main_Control_Create have to provide its own mechanism for ADL calls serialization. */ + ADL_THREADING_LOCKED /*!< ADL will enforce serialization of ADL API when called by multiple threads. Only single thread will be allowed to enter ADL API at the time. This option makes ADL calls thread-safe. You shouldn't use this option if ADL calls will be executed on Linux on x-server rendering thread. It can cause the application to hung. */ +}ADLThreadingModel; + +// @} +/////////////////////////////////////////////////////////////////////////// +// ADLPurposeCode Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLPurposeCode +{ + ADL_PURPOSECODE_NORMAL = 0, + ADL_PURPOSECODE_HIDE_MODE_SWITCH, + ADL_PURPOSECODE_MODE_SWITCH, + ADL_PURPOSECODE_ATTATCH_DEVICE, + ADL_PURPOSECODE_DETACH_DEVICE, + ADL_PURPOSECODE_SETPRIMARY_DEVICE, + ADL_PURPOSECODE_GDI_ROTATION, + ADL_PURPOSECODE_ATI_ROTATION +}; +/////////////////////////////////////////////////////////////////////////// +// ADLAngle Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLAngle +{ + ADL_ANGLE_LANDSCAPE = 0, + ADL_ANGLE_ROTATERIGHT = 90, + ADL_ANGLE_ROTATE180 = 180, + ADL_ANGLE_ROTATELEFT = 270, +}; + +/////////////////////////////////////////////////////////////////////////// +// ADLOrientationDataType Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLOrientationDataType +{ + ADL_ORIENTATIONTYPE_OSDATATYPE, + ADL_ORIENTATIONTYPE_NONOSDATATYPE +}; + +/////////////////////////////////////////////////////////////////////////// +// ADLPanningMode Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLPanningMode +{ + ADL_PANNINGMODE_NO_PANNING = 0, + ADL_PANNINGMODE_AT_LEAST_ONE_NO_PANNING = 1, + ADL_PANNINGMODE_ALLOW_PANNING = 2, +}; + +/////////////////////////////////////////////////////////////////////////// +// ADLLARGEDESKTOPTYPE Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLLARGEDESKTOPTYPE +{ + ADL_LARGEDESKTOPTYPE_NORMALDESKTOP = 0, + ADL_LARGEDESKTOPTYPE_PSEUDOLARGEDESKTOP = 1, + ADL_LARGEDESKTOPTYPE_VERYLARGEDESKTOP = 2 +}; + +/////////////////////////////////////////////////////////////////////////// +// ADLPlatform Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLPlatForm +{ + GRAPHICS_PLATFORM_DESKTOP = 0, + GRAPHICS_PLATFORM_MOBILE = 1 +}; + +/////////////////////////////////////////////////////////////////////////// +// ADLGraphicCoreGeneration Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLGraphicCoreGeneration +{ + ADL_GRAPHIC_CORE_GENERATION_UNDEFINED = 0, + ADL_GRAPHIC_CORE_GENERATION_PRE_GCN = 1, + ADL_GRAPHIC_CORE_GENERATION_GCN = 2, + ADL_GRAPHIC_CORE_GENERATION_RDNA = 3 +}; + +// Other Definitions for internal use + +// Values for ADL_Display_WriteAndReadI2CRev_Get() + +#define ADL_I2C_MAJOR_API_REV 0x00000001 +#define ADL_I2C_MINOR_DEFAULT_API_REV 0x00000000 +#define ADL_I2C_MINOR_OEM_API_REV 0x00000001 + +// Values for ADL_Display_WriteAndReadI2C() +#define ADL_DL_I2C_LINE_OEM 0x00000001 +#define ADL_DL_I2C_LINE_OD_CONTROL 0x00000002 +#define ADL_DL_I2C_LINE_OEM2 0x00000003 +#define ADL_DL_I2C_LINE_OEM3 0x00000004 +#define ADL_DL_I2C_LINE_OEM4 0x00000005 +#define ADL_DL_I2C_LINE_OEM5 0x00000006 +#define ADL_DL_I2C_LINE_OEM6 0x00000007 + +// Max size of I2C data buffer +#define ADL_DL_I2C_MAXDATASIZE 0x00000040 +#define ADL_DL_I2C_MAXWRITEDATASIZE 0x0000000C +#define ADL_DL_I2C_MAXADDRESSLENGTH 0x00000006 +#define ADL_DL_I2C_MAXOFFSETLENGTH 0x00000004 + + +/// Values for ADLDisplayProperty.iPropertyType +#define ADL_DL_DISPLAYPROPERTY_TYPE_UNKNOWN 0 +#define ADL_DL_DISPLAYPROPERTY_TYPE_EXPANSIONMODE 1 +#define ADL_DL_DISPLAYPROPERTY_TYPE_USEUNDERSCANSCALING 2 +/// Enables ITC processing for HDMI panels that are capable of the feature +#define ADL_DL_DISPLAYPROPERTY_TYPE_ITCFLAGENABLE 9 +#define ADL_DL_DISPLAYPROPERTY_TYPE_DOWNSCALE 11 +#define ADL_DL_DISPLAYPROPERTY_TYPE_INTEGER_SCALING 12 + + +/// Values for ADLDisplayContent.iContentType +/// Certain HDMI panels that support ITC have support for a feature such that, the display on the panel +/// can be adjusted to optimize the view of the content being displayed, depending on the type of content. +#define ADL_DL_DISPLAYCONTENT_TYPE_GRAPHICS 1 +#define ADL_DL_DISPLAYCONTENT_TYPE_PHOTO 2 +#define ADL_DL_DISPLAYCONTENT_TYPE_CINEMA 4 +#define ADL_DL_DISPLAYCONTENT_TYPE_GAME 8 + + + +//values for ADLDisplayProperty.iExpansionMode +#define ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_CENTER 0 +#define ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_FULLSCREEN 1 +#define ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_ASPECTRATIO 2 + + +///\defgroup define_dither_states Dithering options +// @{ +/// Dithering disabled. +#define ADL_DL_DISPLAY_DITHER_DISABLED 0 +/// Use default driver settings for dithering. Note that the default setting could be dithering disabled. +#define ADL_DL_DISPLAY_DITHER_DRIVER_DEFAULT 1 +/// Temporal dithering to 6 bpc. Note that if the input is 12 bits, the two least significant bits will be truncated. +#define ADL_DL_DISPLAY_DITHER_FM6 2 +/// Temporal dithering to 8 bpc. +#define ADL_DL_DISPLAY_DITHER_FM8 3 +/// Temporal dithering to 10 bpc. +#define ADL_DL_DISPLAY_DITHER_FM10 4 +/// Spatial dithering to 6 bpc. Note that if the input is 12 bits, the two least significant bits will be truncated. +#define ADL_DL_DISPLAY_DITHER_DITH6 5 +/// Spatial dithering to 8 bpc. +#define ADL_DL_DISPLAY_DITHER_DITH8 6 +/// Spatial dithering to 10 bpc. +#define ADL_DL_DISPLAY_DITHER_DITH10 7 +/// Spatial dithering to 6 bpc. Random number generators are reset every frame, so the same input value of a certain pixel will always be dithered to the same output value. Note that if the input is 12 bits, the two least significant bits will be truncated. +#define ADL_DL_DISPLAY_DITHER_DITH6_NO_FRAME_RAND 8 +/// Spatial dithering to 8 bpc. Random number generators are reset every frame, so the same input value of a certain pixel will always be dithered to the same output value. +#define ADL_DL_DISPLAY_DITHER_DITH8_NO_FRAME_RAND 9 +/// Spatial dithering to 10 bpc. Random number generators are reset every frame, so the same input value of a certain pixel will always be dithered to the same output value. +#define ADL_DL_DISPLAY_DITHER_DITH10_NO_FRAME_RAND 10 +/// Truncation to 6 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN6 11 +/// Truncation to 8 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN8 12 +/// Truncation to 10 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN10 13 +/// Truncation to 10 bpc followed by spatial dithering to 8 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN10_DITH8 14 +/// Truncation to 10 bpc followed by spatial dithering to 6 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN10_DITH6 15 +/// Truncation to 10 bpc followed by temporal dithering to 8 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN10_FM8 16 +/// Truncation to 10 bpc followed by temporal dithering to 6 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN10_FM6 17 +/// Truncation to 10 bpc followed by spatial dithering to 8 bpc and temporal dithering to 6 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN10_DITH8_FM6 18 +/// Spatial dithering to 10 bpc followed by temporal dithering to 8 bpc. +#define ADL_DL_DISPLAY_DITHER_DITH10_FM8 19 +/// Spatial dithering to 10 bpc followed by temporal dithering to 6 bpc. +#define ADL_DL_DISPLAY_DITHER_DITH10_FM6 20 +/// Truncation to 8 bpc followed by spatial dithering to 6 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN8_DITH6 21 +/// Truncation to 8 bpc followed by temporal dithering to 6 bpc. +#define ADL_DL_DISPLAY_DITHER_TRUN8_FM6 22 +/// Spatial dithering to 8 bpc followed by temporal dithering to 6 bpc. +#define ADL_DL_DISPLAY_DITHER_DITH8_FM6 23 +#define ADL_DL_DISPLAY_DITHER_LAST ADL_DL_DISPLAY_DITHER_DITH8_FM6 +// @} + + +/// Display Get Cached EDID flag +#define ADL_MAX_EDIDDATA_SIZE 256 // number of UCHAR +#define ADL_MAX_OVERRIDEEDID_SIZE 512 // number of UCHAR +#define ADL_MAX_EDID_EXTENSION_BLOCKS 3 + +#define ADL_DL_CONTROLLER_OVERLAY_ALPHA 0 +#define ADL_DL_CONTROLLER_OVERLAY_ALPHAPERPIX 1 + +#define ADL_DL_DISPLAY_DATA_PACKET__INFO_PACKET_RESET 0x00000000 +#define ADL_DL_DISPLAY_DATA_PACKET__INFO_PACKET_SET 0x00000001 +#define ADL_DL_DISPLAY_DATA_PACKET__INFO_PACKET_SCAN 0x00000002 + +///\defgroup define_display_packet Display Data Packet Types +// @{ +#define ADL_DL_DISPLAY_DATA_PACKET__TYPE__AVI 0x00000001 +#define ADL_DL_DISPLAY_DATA_PACKET__TYPE__GAMMUT 0x00000002 +#define ADL_DL_DISPLAY_DATA_PACKET__TYPE__VENDORINFO 0x00000004 +#define ADL_DL_DISPLAY_DATA_PACKET__TYPE__HDR 0x00000008 +#define ADL_DL_DISPLAY_DATA_PACKET__TYPE__SPD 0x00000010 +// @} + +// matrix types +#define ADL_GAMUT_MATRIX_SD 1 // SD matrix i.e. BT601 +#define ADL_GAMUT_MATRIX_HD 2 // HD matrix i.e. BT709 + +///\defgroup define_clockinfo_flags Clock flags +/// Used by ADLAdapterODClockInfo.iFlag +// @{ +#define ADL_DL_CLOCKINFO_FLAG_FULLSCREEN3DONLY 0x00000001 +#define ADL_DL_CLOCKINFO_FLAG_ALWAYSFULLSCREEN3D 0x00000002 +#define ADL_DL_CLOCKINFO_FLAG_VPURECOVERYREDUCED 0x00000004 +#define ADL_DL_CLOCKINFO_FLAG_THERMALPROTECTION 0x00000008 +// @} + +// Supported GPUs +// ADL_Display_PowerXpressActiveGPU_Get() +#define ADL_DL_POWERXPRESS_GPU_INTEGRATED 1 +#define ADL_DL_POWERXPRESS_GPU_DISCRETE 2 + +// Possible values for lpOperationResult +// ADL_Display_PowerXpressActiveGPU_Get() +#define ADL_DL_POWERXPRESS_SWITCH_RESULT_STARTED 1 // Switch procedure has been started - Windows platform only +#define ADL_DL_POWERXPRESS_SWITCH_RESULT_DECLINED 2 // Switch procedure cannot be started - All platforms +#define ADL_DL_POWERXPRESS_SWITCH_RESULT_ALREADY 3 // System already has required status - All platforms +#define ADL_DL_POWERXPRESS_SWITCH_RESULT_DEFERRED 5 // Switch was deferred and requires an X restart - Linux platform only + +// PowerXpress support version +// ADL_Display_PowerXpressVersion_Get() +#define ADL_DL_POWERXPRESS_VERSION_MAJOR 2 // Current PowerXpress support version 2.0 +#define ADL_DL_POWERXPRESS_VERSION_MINOR 0 + +#define ADL_DL_POWERXPRESS_VERSION (((ADL_DL_POWERXPRESS_VERSION_MAJOR) << 16) | ADL_DL_POWERXPRESS_VERSION_MINOR) + +//values for ADLThermalControllerInfo.iThermalControllerDomain +#define ADL_DL_THERMAL_DOMAIN_OTHER 0 +#define ADL_DL_THERMAL_DOMAIN_GPU 1 + +//values for ADLThermalControllerInfo.iFlags +#define ADL_DL_THERMAL_FLAG_INTERRUPT 1 +#define ADL_DL_THERMAL_FLAG_FANCONTROL 2 + +///\defgroup define_fanctrl Fan speed cotrol +/// Values for ADLFanSpeedInfo.iFlags +// @{ +#define ADL_DL_FANCTRL_SUPPORTS_PERCENT_READ 1 +#define ADL_DL_FANCTRL_SUPPORTS_PERCENT_WRITE 2 +#define ADL_DL_FANCTRL_SUPPORTS_RPM_READ 4 +#define ADL_DL_FANCTRL_SUPPORTS_RPM_WRITE 8 +// @} + +//values for ADLFanSpeedValue.iSpeedType +#define ADL_DL_FANCTRL_SPEED_TYPE_PERCENT 1 +#define ADL_DL_FANCTRL_SPEED_TYPE_RPM 2 + +//values for ADLFanSpeedValue.iFlags +#define ADL_DL_FANCTRL_FLAG_USER_DEFINED_SPEED 1 + +// MVPU interfaces +#define ADL_DL_MAX_MVPU_ADAPTERS 4 +#define MVPU_ADAPTER_0 0x00000001 +#define MVPU_ADAPTER_1 0x00000002 +#define MVPU_ADAPTER_2 0x00000004 +#define MVPU_ADAPTER_3 0x00000008 +#define ADL_DL_MAX_REGISTRY_PATH 256 + +//values for ADLMVPUStatus.iStatus +#define ADL_DL_MVPU_STATUS_OFF 0 +#define ADL_DL_MVPU_STATUS_ON 1 + +// values for ASIC family +///\defgroup define_Asic_type Detailed asic types +/// Defines for Adapter ASIC family type +// @{ +#define ADL_ASIC_UNDEFINED 0 +#define ADL_ASIC_DISCRETE (1 << 0) +#define ADL_ASIC_INTEGRATED (1 << 1) +#define ADL_ASIC_FIREGL (1 << 2) +#define ADL_ASIC_FIREMV (1 << 3) +#define ADL_ASIC_XGP (1 << 4) +#define ADL_ASIC_FUSION (1 << 5) +#define ADL_ASIC_FIRESTREAM (1 << 6) +#define ADL_ASIC_EMBEDDED (1 << 7) +// @} + +///\defgroup define_detailed_timing_flags Detailed Timimg Flags +/// Defines for ADLDetailedTiming.sTimingFlags field +// @{ +#define ADL_DL_TIMINGFLAG_DOUBLE_SCAN 0x0001 +//sTimingFlags is set when the mode is INTERLACED, if not PROGRESSIVE +#define ADL_DL_TIMINGFLAG_INTERLACED 0x0002 +//sTimingFlags is set when the Horizontal Sync is POSITIVE, if not NEGATIVE +#define ADL_DL_TIMINGFLAG_H_SYNC_POLARITY 0x0004 +//sTimingFlags is set when the Vertical Sync is POSITIVE, if not NEGATIVE +#define ADL_DL_TIMINGFLAG_V_SYNC_POLARITY 0x0008 +// @} + +///\defgroup define_modetiming_standard Timing Standards +/// Defines for ADLDisplayModeInfo.iTimingStandard field +// @{ +#define ADL_DL_MODETIMING_STANDARD_CVT 0x00000001 // CVT Standard +#define ADL_DL_MODETIMING_STANDARD_GTF 0x00000002 // GFT Standard +#define ADL_DL_MODETIMING_STANDARD_DMT 0x00000004 // DMT Standard +#define ADL_DL_MODETIMING_STANDARD_CUSTOM 0x00000008 // User-defined standard +#define ADL_DL_MODETIMING_STANDARD_DRIVER_DEFAULT 0x00000010 // Remove Mode from overriden list +#define ADL_DL_MODETIMING_STANDARD_CVT_RB 0x00000020 // CVT-RB Standard +// @} + +// \defgroup define_xserverinfo driver x-server info +/// These flags are used by ADL_XServerInfo_Get() +// @ + +/// Xinerama is active in the x-server, Xinerama extension may report it to be active but it +/// may not be active in x-server +#define ADL_XSERVERINFO_XINERAMAACTIVE (1<<0) + +/// RandR 1.2 is supported by driver, RandR extension may report version 1.2 +/// but driver may not support it +#define ADL_XSERVERINFO_RANDR12SUPPORTED (1<<1) +// @ + + +///\defgroup define_eyefinity_constants Eyefinity Definitions +// @{ + +#define ADL_CONTROLLERVECTOR_0 1 // ADL_CONTROLLERINDEX_0 = 0, (1 << ADL_CONTROLLERINDEX_0) +#define ADL_CONTROLLERVECTOR_1 2 // ADL_CONTROLLERINDEX_1 = 1, (1 << ADL_CONTROLLERINDEX_1) + +#define ADL_DISPLAY_SLSGRID_ORIENTATION_000 0x00000001 +#define ADL_DISPLAY_SLSGRID_ORIENTATION_090 0x00000002 +#define ADL_DISPLAY_SLSGRID_ORIENTATION_180 0x00000004 +#define ADL_DISPLAY_SLSGRID_ORIENTATION_270 0x00000008 +#define ADL_DISPLAY_SLSGRID_CAP_OPTION_RELATIVETO_LANDSCAPE 0x00000001 +#define ADL_DISPLAY_SLSGRID_CAP_OPTION_RELATIVETO_CURRENTANGLE 0x00000002 +#define ADL_DISPLAY_SLSGRID_PORTAIT_MODE 0x00000004 +#define ADL_DISPLAY_SLSGRID_KEEPTARGETROTATION 0x00000080 + +#define ADL_DISPLAY_SLSGRID_SAMEMODESLS_SUPPORT 0x00000010 +#define ADL_DISPLAY_SLSGRID_MIXMODESLS_SUPPORT 0x00000020 +#define ADL_DISPLAY_SLSGRID_DISPLAYROTATION_SUPPORT 0x00000040 +#define ADL_DISPLAY_SLSGRID_DESKTOPROTATION_SUPPORT 0x00000080 + + +#define ADL_DISPLAY_SLSMAP_SLSLAYOUTMODE_FIT 0x0100 +#define ADL_DISPLAY_SLSMAP_SLSLAYOUTMODE_FILL 0x0200 +#define ADL_DISPLAY_SLSMAP_SLSLAYOUTMODE_EXPAND 0x0400 + +#define ADL_DISPLAY_SLSMAP_IS_SLS 0x1000 +#define ADL_DISPLAY_SLSMAP_IS_SLSBUILDER 0x2000 +#define ADL_DISPLAY_SLSMAP_IS_CLONEVT 0x4000 + +#define ADL_DISPLAY_SLSMAPCONFIG_GET_OPTION_RELATIVETO_LANDSCAPE 0x00000001 +#define ADL_DISPLAY_SLSMAPCONFIG_GET_OPTION_RELATIVETO_CURRENTANGLE 0x00000002 + +#define ADL_DISPLAY_SLSMAPCONFIG_CREATE_OPTION_RELATIVETO_LANDSCAPE 0x00000001 +#define ADL_DISPLAY_SLSMAPCONFIG_CREATE_OPTION_RELATIVETO_CURRENTANGLE 0x00000002 + +#define ADL_DISPLAY_SLSMAPCONFIG_REARRANGE_OPTION_RELATIVETO_LANDSCAPE 0x00000001 +#define ADL_DISPLAY_SLSMAPCONFIG_REARRANGE_OPTION_RELATIVETO_CURRENTANGLE 0x00000002 + +#define ADL_SLS_SAMEMODESLS_SUPPORT 0x0001 +#define ADL_SLS_MIXMODESLS_SUPPORT 0x0002 +#define ADL_SLS_DISPLAYROTATIONSLS_SUPPORT 0x0004 +#define ADL_SLS_DESKTOPROTATIONSLS_SUPPORT 0x0008 + +#define ADL_SLS_TARGETS_INVALID 0x0001 +#define ADL_SLS_MODES_INVALID 0x0002 +#define ADL_SLS_ROTATIONS_INVALID 0x0004 +#define ADL_SLS_POSITIONS_INVALID 0x0008 +#define ADL_SLS_LAYOUTMODE_INVALID 0x0010 + +#define ADL_DISPLAY_SLSDISPLAYOFFSET_VALID 0x0002 + +#define ADL_DISPLAY_SLSGRID_RELATIVETO_LANDSCAPE 0x00000010 +#define ADL_DISPLAY_SLSGRID_RELATIVETO_CURRENTANGLE 0x00000020 + + +/// The bit mask identifies displays is currently in bezel mode. +#define ADL_DISPLAY_SLSMAP_BEZELMODE 0x00000010 +/// The bit mask identifies displays from this map is arranged. +#define ADL_DISPLAY_SLSMAP_DISPLAYARRANGED 0x00000002 +/// The bit mask identifies this map is currently in used for the current adapter. +#define ADL_DISPLAY_SLSMAP_CURRENTCONFIG 0x00000004 + +///For onlay active SLS map info +#define ADL_DISPLAY_SLSMAPINDEXLIST_OPTION_ACTIVE 0x00000001 + +///For Bezel +#define ADL_DISPLAY_BEZELOFFSET_STEPBYSTEPSET 0x00000004 +#define ADL_DISPLAY_BEZELOFFSET_COMMIT 0x00000008 + +typedef enum _SLS_ImageCropType { + Fit = 1, + Fill = 2, + Expand = 3 +}SLS_ImageCropType; + + +typedef enum _DceSettingsType { + DceSetting_HdmiLq, + DceSetting_DpSettings, + DceSetting_Protection +} DceSettingsType; + +typedef enum _DpLinkRate { + DPLinkRate_Unknown, + DPLinkRate_RBR, + DPLinkRate_HBR, + DPLinkRate_HBR2, + DPLinkRate_HBR3 +} DpLinkRate; + +// @} + +///\defgroup define_powerxpress_constants PowerXpress Definitions +/// @{ + +/// The bit mask identifies PX caps for ADLPXConfigCaps.iPXConfigCapMask and ADLPXConfigCaps.iPXConfigCapValue +#define ADL_PX_CONFIGCAPS_SPLASHSCREEN_SUPPORT 0x0001 +#define ADL_PX_CONFIGCAPS_CF_SUPPORT 0x0002 +#define ADL_PX_CONFIGCAPS_MUXLESS 0x0004 +#define ADL_PX_CONFIGCAPS_PROFILE_COMPLIANT 0x0008 +#define ADL_PX_CONFIGCAPS_NON_AMD_DRIVEN_DISPLAYS 0x0010 +#define ADL_PX_CONFIGCAPS_FIXED_SUPPORT 0x0020 +#define ADL_PX_CONFIGCAPS_DYNAMIC_SUPPORT 0x0040 +#define ADL_PX_CONFIGCAPS_HIDE_AUTO_SWITCH 0x0080 + +/// The bit mask identifies PX schemes for ADLPXSchemeRange +#define ADL_PX_SCHEMEMASK_FIXED 0x0001 +#define ADL_PX_SCHEMEMASK_DYNAMIC 0x0002 + +/// PX Schemes +typedef enum _ADLPXScheme +{ + ADL_PX_SCHEME_INVALID = 0, + ADL_PX_SCHEME_FIXED = ADL_PX_SCHEMEMASK_FIXED, + ADL_PX_SCHEME_DYNAMIC = ADL_PX_SCHEMEMASK_DYNAMIC +}ADLPXScheme; + +/// Just keep the old definitions for compatibility, need to be removed later +typedef enum PXScheme +{ + PX_SCHEME_INVALID = 0, + PX_SCHEME_FIXED = 1, + PX_SCHEME_DYNAMIC = 2 +} PXScheme; + + +/// @} + +///\defgroup define_appprofiles For Application Profiles +/// @{ + +#define ADL_APP_PROFILE_FILENAME_LENGTH 256 +#define ADL_APP_PROFILE_TIMESTAMP_LENGTH 32 +#define ADL_APP_PROFILE_VERSION_LENGTH 32 +#define ADL_APP_PROFILE_PROPERTY_LENGTH 64 + +enum ApplicationListType +{ + ADL_PX40_MRU, + ADL_PX40_MISSED, + ADL_PX40_DISCRETE, + ADL_PX40_INTEGRATED, + ADL_MMD_PROFILED, + ADL_PX40_TOTAL +}; + +typedef enum _ADLProfilePropertyType +{ + ADL_PROFILEPROPERTY_TYPE_BINARY = 0, + ADL_PROFILEPROPERTY_TYPE_BOOLEAN, + ADL_PROFILEPROPERTY_TYPE_DWORD, + ADL_PROFILEPROPERTY_TYPE_QWORD, + ADL_PROFILEPROPERTY_TYPE_ENUMERATED, + ADL_PROFILEPROPERTY_TYPE_STRING +}ADLProfilePropertyType; + + +/// @} + +///\defgroup define_dp12 For Display Port 1.2 +/// @{ + +/// Maximum Relative Address Link +#define ADL_MAX_RAD_LINK_COUNT 15 + +/// @} + +///\defgroup defines_gamutspace Driver Supported Gamut Space +/// @{ + +/// The flags desribes that gamut is related to source or to destination and to overlay or to graphics +#define ADL_GAMUT_REFERENCE_SOURCE (1 << 0) +#define ADL_GAMUT_GAMUT_VIDEO_CONTENT (1 << 1) + +/// The flags are used to describe the source of gamut and how read information from struct ADLGamutData +#define ADL_CUSTOM_WHITE_POINT (1 << 0) +#define ADL_CUSTOM_GAMUT (1 << 1) +#define ADL_GAMUT_REMAP_ONLY (1 << 2) + +/// The define means the predefined gamut values . +///Driver uses to find entry in the table and apply appropriate gamut space. +#define ADL_GAMUT_SPACE_CCIR_709 (1 << 0) +#define ADL_GAMUT_SPACE_CCIR_601 (1 << 1) +#define ADL_GAMUT_SPACE_ADOBE_RGB (1 << 2) +#define ADL_GAMUT_SPACE_CIE_RGB (1 << 3) +#define ADL_GAMUT_SPACE_CUSTOM (1 << 4) +#define ADL_GAMUT_SPACE_CCIR_2020 (1 << 5) +#define ADL_GAMUT_SPACE_APPCTRL (1 << 6) + +/// Predefine white point values are structed similar to gamut . +#define ADL_WHITE_POINT_5000K (1 << 0) +#define ADL_WHITE_POINT_6500K (1 << 1) +#define ADL_WHITE_POINT_7500K (1 << 2) +#define ADL_WHITE_POINT_9300K (1 << 3) +#define ADL_WHITE_POINT_CUSTOM (1 << 4) + +///gamut and white point coordinates are from 0.0 -1.0 and divider is used to find the real value . +/// X float = X int /divider +#define ADL_GAMUT_WHITEPOINT_DIVIDER 10000 + +///gamma a0 coefficient uses the following divider: +#define ADL_REGAMMA_COEFFICIENT_A0_DIVIDER 10000000 +///gamma a1 ,a2,a3 coefficients use the following divider: +#define ADL_REGAMMA_COEFFICIENT_A1A2A3_DIVIDER 1000 + +///describes whether the coefficients are from EDID or custom user values. +#define ADL_EDID_REGAMMA_COEFFICIENTS (1 << 0) +///Used for struct ADLRegamma. Feature if set use gamma ramp, if missing use regamma coefficents +#define ADL_USE_GAMMA_RAMP (1 << 4) +///Used for struct ADLRegamma. If the gamma ramp flag is used then the driver could apply de gamma corretion to the supplied curve and this depends on this flag +#define ADL_APPLY_DEGAMMA (1 << 5) +///specifies that standard SRGB gamma should be applied +#define ADL_EDID_REGAMMA_PREDEFINED_SRGB (1 << 1) +///specifies that PQ gamma curve should be applied +#define ADL_EDID_REGAMMA_PREDEFINED_PQ (1 << 2) +///specifies that PQ gamma curve should be applied, lower max nits +#define ADL_EDID_REGAMMA_PREDEFINED_PQ_2084_INTERIM (1 << 3) +///specifies that 3.6 gamma should be applied +#define ADL_EDID_REGAMMA_PREDEFINED_36 (1 << 6) +///specifies that BT709 gama should be applied +#define ADL_EDID_REGAMMA_PREDEFINED_BT709 (1 << 7) +///specifies that regamma should be disabled, and application controls regamma content (of the whole screen) +#define ADL_EDID_REGAMMA_PREDEFINED_APPCTRL (1 << 8) + +/// @} + +/// \defgroup define_ddcinfo_pixelformats DDCInfo Pixel Formats +/// @{ +/// defines for iPanelPixelFormat in struct ADLDDCInfo2 +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_RGB656 0x00000001L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_RGB666 0x00000002L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_RGB888 0x00000004L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_RGB101010 0x00000008L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_RGB161616 0x00000010L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_RGB_RESERVED1 0x00000020L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_RGB_RESERVED2 0x00000040L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_RGB_RESERVED3 0x00000080L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_XRGB_BIAS101010 0x00000100L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR444_8BPCC 0x00000200L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR444_10BPCC 0x00000400L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR444_12BPCC 0x00000800L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR422_8BPCC 0x00001000L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR422_10BPCC 0x00002000L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR422_12BPCC 0x00004000L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR420_8BPCC 0x00008000L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR420_10BPCC 0x00010000L +#define ADL_DISPLAY_DDCINFO_PIXEL_FORMAT_YCBCR420_12BPCC 0x00020000L +/// @} + +/// \defgroup define_source_content_TF ADLSourceContentAttributes transfer functions (gamma) +/// @{ +/// defines for iTransferFunction in ADLSourceContentAttributes +#define ADL_TF_sRGB 0x0001 ///< sRGB +#define ADL_TF_BT709 0x0002 ///< BT.709 +#define ADL_TF_PQ2084 0x0004 ///< PQ2084 +#define ADL_TF_PQ2084_INTERIM 0x0008 ///< PQ2084-Interim +#define ADL_TF_LINEAR_0_1 0x0010 ///< Linear 0 - 1 +#define ADL_TF_LINEAR_0_125 0x0020 ///< Linear 0 - 125 +#define ADL_TF_DOLBYVISION 0x0040 ///< DolbyVision +#define ADL_TF_GAMMA_22 0x0080 ///< Plain 2.2 gamma curve +/// @} + +/// \defgroup define_source_content_CS ADLSourceContentAttributes color spaces +/// @{ +/// defines for iColorSpace in ADLSourceContentAttributes +#define ADL_CS_sRGB 0x0001 ///< sRGB +#define ADL_CS_BT601 0x0002 ///< BT.601 +#define ADL_CS_BT709 0x0004 ///< BT.709 +#define ADL_CS_BT2020 0x0008 ///< BT.2020 +#define ADL_CS_ADOBE 0x0010 ///< Adobe RGB +#define ADL_CS_P3 0x0020 ///< DCI-P3 +#define ADL_CS_scRGB_MS_REF 0x0040 ///< scRGB (MS Reference) +#define ADL_CS_DISPLAY_NATIVE 0x0080 ///< Display Native +#define ADL_CS_APP_CONTROL 0x0100 ///< Application Controlled +#define ADL_CS_DOLBYVISION 0x0200 ///< DolbyVision +/// @} + +/// \defgroup define_HDR_support ADLDDCInfo2 HDR support options +/// @{ +/// defines for iSupportedHDR in ADLDDCInfo2 +#define ADL_HDR_CEA861_3 0x0001 ///< HDR10/CEA861.3 HDR supported +#define ADL_HDR_DOLBYVISION 0x0002 ///< DolbyVision HDR supported +#define ADL_HDR_FREESYNC_HDR 0x0004 ///< FreeSync HDR supported +/// @} + +/// \defgroup define_FreesyncFlags ADLDDCInfo2 Freesync HDR flags +/// @{ +/// defines for iFreesyncFlags in ADLDDCInfo2 +#define ADL_HDR_FREESYNC_BACKLIGHT_SUPPORT 0x0001 ///< Global backlight control supported +#define ADL_HDR_FREESYNC_LOCAL_DIMMING 0x0002 ///< Local dimming supported +/// @} + +/// \defgroup define_source_content_flags ADLSourceContentAttributes flags +/// @{ +/// defines for iFlags in ADLSourceContentAttributes +#define ADL_SCA_LOCAL_DIMMING_DISABLE 0x0001 ///< Disable local dimming +/// @} + +/// \defgroup define_dbd_state Deep Bit Depth +/// @{ + +/// defines for ADL_Workstation_DeepBitDepth_Get and ADL_Workstation_DeepBitDepth_Set functions +// This value indicates that the deep bit depth state is forced off +#define ADL_DEEPBITDEPTH_FORCEOFF 0 +/// This value indicates that the deep bit depth state is set to auto, the driver will automatically enable the +/// appropriate deep bit depth state depending on what connected display supports. +#define ADL_DEEPBITDEPTH_10BPP_AUTO 1 +/// This value indicates that the deep bit depth state is forced on to 10 bits per pixel, this is regardless if the display +/// supports 10 bpp. +#define ADL_DEEPBITDEPTH_10BPP_FORCEON 2 + +/// defines for ADLAdapterConfigMemory of ADL_Adapter_ConfigMemory_Get +/// If this bit is set, it indicates that the Deep Bit Depth pixel is set on the display +#define ADL_ADAPTER_CONFIGMEMORY_DBD (1 << 0) +/// If this bit is set, it indicates that the display is rotated (90, 180 or 270) +#define ADL_ADAPTER_CONFIGMEMORY_ROTATE (1 << 1) +/// If this bit is set, it indicates that passive stereo is set on the display +#define ADL_ADAPTER_CONFIGMEMORY_STEREO_PASSIVE (1 << 2) +/// If this bit is set, it indicates that the active stereo is set on the display +#define ADL_ADAPTER_CONFIGMEMORY_STEREO_ACTIVE (1 << 3) +/// If this bit is set, it indicates that the tear free vsync is set on the display +#define ADL_ADAPTER_CONFIGMEMORY_ENHANCEDVSYNC (1 << 4) +#define ADL_ADAPTER_CONFIGMEMORY_TEARFREEVSYNC (1 << 4) +/// @} + +/// \defgroup define_adl_validmemoryrequiredfields Memory Type +/// @{ + +/// This group defines memory types in ADLMemoryRequired struct \n +/// Indicates that this is the visible memory +#define ADL_MEMORYREQTYPE_VISIBLE (1 << 0) +/// Indicates that this is the invisible memory. +#define ADL_MEMORYREQTYPE_INVISIBLE (1 << 1) +/// Indicates that this is amount of visible memory per GPU that should be reserved for all other allocations. +#define ADL_MEMORYREQTYPE_GPURESERVEDVISIBLE (1 << 2) +/// @} + +/// \defgroup define_adapter_tear_free_status +/// Used in ADL_Adapter_TEAR_FREE_Set and ADL_Adapter_TFD_Get functions to indicate the tear free +/// desktop status. +/// @{ +/// Tear free desktop is enabled. +#define ADL_ADAPTER_TEAR_FREE_ON 1 +/// Tear free desktop can't be enabled due to a lack of graphic adapter memory. +#define ADL_ADAPTER_TEAR_FREE_NOTENOUGHMEM -1 +/// Tear free desktop can't be enabled due to quad buffer stereo being enabled. +#define ADL_ADAPTER_TEAR_FREE_OFF_ERR_QUADBUFFERSTEREO -2 +/// Tear free desktop can't be enabled due to MGPU-SLS being enabled. +#define ADL_ADAPTER_TEAR_FREE_OFF_ERR_MGPUSLD -3 +/// Tear free desktop is disabled. +#define ADL_ADAPTER_TEAR_FREE_OFF 0 +/// @} + +/// \defgroup define_adapter_crossdisplay_platforminfo +/// Used in ADL_Adapter_CrossDisplayPlatformInfo_Get function to indicate the Crossdisplay platform info. +/// @{ +/// CROSSDISPLAY platform. +#define ADL_CROSSDISPLAY_PLATFORM (1 << 0) +/// CROSSDISPLAY platform for Lasso station. +#define ADL_CROSSDISPLAY_PLATFORM_LASSO (1 << 1) +/// CROSSDISPLAY platform for docking station. +#define ADL_CROSSDISPLAY_PLATFORM_DOCKSTATION (1 << 2) +/// @} + +/// \defgroup define_adapter_crossdisplay_option +/// Used in ADL_Adapter_CrossdisplayInfoX2_Set function to indicate cross display options. +/// @{ +/// Checking if 3D application is runnning. If yes, not to do switch, return ADL_OK_WAIT; otherwise do switch. +#define ADL_CROSSDISPLAY_OPTION_NONE 0 +/// Force switching without checking for running 3D applications +#define ADL_CROSSDISPLAY_OPTION_FORCESWITCH (1 << 0) +/// @} + +/// \defgroup define_adapter_states Adapter Capabilities +/// These defines the capabilities supported by an adapter. It is used by \ref ADL_Adapter_ConfigureState_Get +/// @{ +/// Indicates that the adapter is headless (i.e. no displays can be connected to it) +#define ADL_ADAPTERCONFIGSTATE_HEADLESS ( 1 << 2 ) +/// Indicates that the adapter is configured to define the main rendering capabilities. For example, adapters +/// in Crossfire(TM) configuration, this bit would only be set on the adapter driving the display(s). +#define ADL_ADAPTERCONFIGSTATE_REQUISITE_RENDER ( 1 << 0 ) +/// Indicates that the adapter is configured to be used to unload some of the rendering work for a particular +/// requisite rendering adapter. For eample, for adapters in a Crossfire configuration, this bit would be set +/// on all adapters that are currently not driving the display(s) +#define ADL_ADAPTERCONFIGSTATE_ANCILLARY_RENDER ( 1 << 1 ) +/// Indicates that scatter gather feature enabled on the adapter +#define ADL_ADAPTERCONFIGSTATE_SCATTERGATHER ( 1 << 4 ) +/// @} + +/// \defgroup define_controllermode_ulModifiers +/// These defines the detailed actions supported by set viewport. It is used by \ref ADL_Display_ViewPort_Set +/// @{ +/// Indicate that the viewport set will change the view position +#define ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_POSITION 0x00000001 +/// Indicate that the viewport set will change the view PanLock +#define ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_PANLOCK 0x00000002 +/// Indicate that the viewport set will change the view size +#define ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_SIZE 0x00000008 +/// @} + +/// \defgroup defines for Mirabilis +/// These defines are used for the Mirabilis feature +/// @{ +/// +/// Indicates the maximum number of audio sample rates +#define ADL_MAX_AUDIO_SAMPLE_RATE_COUNT 16 +/// @} + +/////////////////////////////////////////////////////////////////////////// +// ADLMultiChannelSplitStateFlag Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLMultiChannelSplitStateFlag +{ + ADLMultiChannelSplit_Unitialized = 0, + ADLMultiChannelSplit_Disabled = 1, + ADLMultiChannelSplit_Enabled = 2, + ADLMultiChannelSplit_SaveProfile = 3 +}; + +/////////////////////////////////////////////////////////////////////////// +// ADLSampleRate Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLSampleRate +{ + ADLSampleRate_32KHz =0, + ADLSampleRate_44P1KHz, + ADLSampleRate_48KHz, + ADLSampleRate_88P2KHz, + ADLSampleRate_96KHz, + ADLSampleRate_176P4KHz, + ADLSampleRate_192KHz, + ADLSampleRate_384KHz, //DP1.2 + ADLSampleRate_768KHz, //DP1.2 + ADLSampleRate_Undefined +}; + +/// \defgroup define_overdrive6_capabilities +/// These defines the capabilities supported by Overdrive 6. It is used by \ref ADL_Overdrive6_Capabilities_Get +// @{ +/// Indicate that core (engine) clock can be changed. +#define ADL_OD6_CAPABILITY_SCLK_CUSTOMIZATION 0x00000001 +/// Indicate that memory clock can be changed. +#define ADL_OD6_CAPABILITY_MCLK_CUSTOMIZATION 0x00000002 +/// Indicate that graphics activity reporting is supported. +#define ADL_OD6_CAPABILITY_GPU_ACTIVITY_MONITOR 0x00000004 +/// Indicate that power limit can be customized. +#define ADL_OD6_CAPABILITY_POWER_CONTROL 0x00000008 +/// Indicate that SVI2 Voltage Control is supported. +#define ADL_OD6_CAPABILITY_VOLTAGE_CONTROL 0x00000010 +/// Indicate that OD6+ percentage adjustment is supported. +#define ADL_OD6_CAPABILITY_PERCENT_ADJUSTMENT 0x00000020 +/// Indicate that Thermal Limit Unlock is supported. +#define ADL_OD6_CAPABILITY_THERMAL_LIMIT_UNLOCK 0x00000040 +///Indicate that Fan speed needs to be displayed in RPM +#define ADL_OD6_CAPABILITY_FANSPEED_IN_RPM 0x00000080 +// @} + +/// \defgroup define_overdrive6_supported_states +/// These defines the power states supported by Overdrive 6. It is used by \ref ADL_Overdrive6_Capabilities_Get +// @{ +/// Indicate that overdrive is supported in the performance state. This is currently the only state supported. +#define ADL_OD6_SUPPORTEDSTATE_PERFORMANCE 0x00000001 +/// Do not use. Reserved for future use. +#define ADL_OD6_SUPPORTEDSTATE_POWER_SAVING 0x00000002 +// @} + +/// \defgroup define_overdrive6_getstateinfo +/// These defines the power states to get information about. It is used by \ref ADL_Overdrive6_StateInfo_Get +// @{ +/// Get default clocks for the performance state. +#define ADL_OD6_GETSTATEINFO_DEFAULT_PERFORMANCE 0x00000001 +/// Do not use. Reserved for future use. +#define ADL_OD6_GETSTATEINFO_DEFAULT_POWER_SAVING 0x00000002 +/// Get clocks for current state. Currently this is the same as \ref ADL_OD6_GETSTATEINFO_CUSTOM_PERFORMANCE +/// since only performance state is supported. +#define ADL_OD6_GETSTATEINFO_CURRENT 0x00000003 +/// Get the modified clocks (if any) for the performance state. If clocks were not modified +/// through Overdrive 6, then this will return the same clocks as \ref ADL_OD6_GETSTATEINFO_DEFAULT_PERFORMANCE. +#define ADL_OD6_GETSTATEINFO_CUSTOM_PERFORMANCE 0x00000004 +/// Do not use. Reserved for future use. +#define ADL_OD6_GETSTATEINFO_CUSTOM_POWER_SAVING 0x00000005 +// @} + +/// \defgroup define_overdrive6_getstate and define_overdrive6_getmaxclockadjust +/// These defines the power states to get information about. It is used by \ref ADL_Overdrive6_StateEx_Get and \ref ADL_Overdrive6_MaxClockAdjust_Get +// @{ +/// Get default clocks for the performance state. Only performance state is currently supported. +#define ADL_OD6_STATE_PERFORMANCE 0x00000001 +// @} + +/// \defgroup define_overdrive6_setstate +/// These define which power state to set customized clocks on. It is used by \ref ADL_Overdrive6_State_Set +// @{ +/// Set customized clocks for the performance state. +#define ADL_OD6_SETSTATE_PERFORMANCE 0x00000001 +/// Do not use. Reserved for future use. +#define ADL_OD6_SETSTATE_POWER_SAVING 0x00000002 +// @} + +/// \defgroup define_overdrive6_thermalcontroller_caps +/// These defines the capabilities of the GPU thermal controller. It is used by \ref ADL_Overdrive6_ThermalController_Caps +// @{ +/// GPU thermal controller is supported. +#define ADL_OD6_TCCAPS_THERMAL_CONTROLLER 0x00000001 +/// GPU fan speed control is supported. +#define ADL_OD6_TCCAPS_FANSPEED_CONTROL 0x00000002 +/// Fan speed percentage can be read. +#define ADL_OD6_TCCAPS_FANSPEED_PERCENT_READ 0x00000100 +/// Fan speed can be set by specifying a percentage value. +#define ADL_OD6_TCCAPS_FANSPEED_PERCENT_WRITE 0x00000200 +/// Fan speed RPM (revolutions-per-minute) can be read. +#define ADL_OD6_TCCAPS_FANSPEED_RPM_READ 0x00000400 +/// Fan speed can be set by specifying an RPM value. +#define ADL_OD6_TCCAPS_FANSPEED_RPM_WRITE 0x00000800 +// @} + +/// \defgroup define_overdrive6_fanspeed_type +/// These defines the fan speed type being reported. It is used by \ref ADL_Overdrive6_FanSpeed_Get +// @{ +/// Fan speed reported in percentage. +#define ADL_OD6_FANSPEED_TYPE_PERCENT 0x00000001 +/// Fan speed reported in RPM. +#define ADL_OD6_FANSPEED_TYPE_RPM 0x00000002 +/// Fan speed has been customized by the user, and fan is not running in automatic mode. +#define ADL_OD6_FANSPEED_USER_DEFINED 0x00000100 +// @} + +/// \defgroup define_overdrive_EventCounter_type +/// These defines the EventCounter type being reported. It is used by \ref ADL2_OverdriveN_CountOfEvents_Get ,can be used on older OD version supported ASICs also. +// @{ +#define ADL_ODN_EVENTCOUNTER_THERMAL 0 +#define ADL_ODN_EVENTCOUNTER_VPURECOVERY 1 +// @} + +/////////////////////////////////////////////////////////////////////////// +// ADLODNControlType Enumeration +/////////////////////////////////////////////////////////////////////////// +enum ADLODNControlType +{ + ODNControlType_Current = 0, + ODNControlType_Default, + ODNControlType_Auto, + ODNControlType_Manual +}; + +enum ADLODNDPMMaskType +{ + ADL_ODN_DPM_CLOCK = 1 << 0, + ADL_ODN_DPM_VDDC = 1 << 1, + ADL_ODN_DPM_MASK = 1 << 2, +}; + +//ODN features Bits for ADLODNCapabilitiesX2 +enum ADLODNFeatureControl +{ + ADL_ODN_SCLK_DPM = 1 << 0, + ADL_ODN_MCLK_DPM = 1 << 1, + ADL_ODN_SCLK_VDD = 1 << 2, + ADL_ODN_MCLK_VDD = 1 << 3, + ADL_ODN_FAN_SPEED_MIN = 1 << 4, + ADL_ODN_FAN_SPEED_TARGET = 1 << 5, + ADL_ODN_ACOUSTIC_LIMIT_SCLK = 1 << 6, + ADL_ODN_TEMPERATURE_FAN_MAX = 1 << 7, + ADL_ODN_TEMPERATURE_SYSTEM = 1 << 8, + ADL_ODN_POWER_LIMIT = 1 << 9, + ADL_ODN_SCLK_AUTO_LIMIT = 1 << 10, + ADL_ODN_MCLK_AUTO_LIMIT = 1 << 11, + ADL_ODN_SCLK_DPM_MASK_ENABLE = 1 << 12, + ADL_ODN_MCLK_DPM_MASK_ENABLE = 1 << 13, + ADL_ODN_MCLK_UNDERCLOCK_ENABLE = 1 << 14, + ADL_ODN_SCLK_DPM_THROTTLE_NOTIFY = 1 << 15, + ADL_ODN_POWER_UTILIZATION = 1 << 16, + ADL_ODN_PERF_TUNING_SLIDER = 1 << 17, + ADL_ODN_REMOVE_WATTMAN_PAGE = 1 << 31 // Internal Only +}; + +//If any new feature is added, PPLIB only needs to add ext feature ID and Item ID(Seeting ID). These IDs should match the drive defined in CWDDEPM.h +enum ADLODNExtFeatureControl +{ + ADL_ODN_EXT_FEATURE_MEMORY_TIMING_TUNE = 1 << 0, + ADL_ODN_EXT_FEATURE_FAN_ZERO_RPM_CONTROL = 1 << 1, + ADL_ODN_EXT_FEATURE_AUTO_UV_ENGINE = 1 << 2, //Auto under voltage + ADL_ODN_EXT_FEATURE_AUTO_OC_ENGINE = 1 << 3, //Auto OC Enine + ADL_ODN_EXT_FEATURE_AUTO_OC_MEMORY = 1 << 4, //Auto OC memory + ADL_ODN_EXT_FEATURE_FAN_CURVE = 1 << 5 //Fan curve + +}; + +//If any new feature is added, PPLIB only needs to add ext feature ID and Item ID(Seeting ID).These IDs should match the drive defined in CWDDEPM.h +enum ADLODNExtSettingId +{ + ADL_ODN_PARAMETER_AC_TIMING = 0, + ADL_ODN_PARAMETER_FAN_ZERO_RPM_CONTROL, + ADL_ODN_PARAMETER_AUTO_UV_ENGINE, + ADL_ODN_PARAMETER_AUTO_OC_ENGINE, + ADL_ODN_PARAMETER_AUTO_OC_MEMORY, + ADL_ODN_PARAMETER_FAN_CURVE_TEMPERATURE_1, + ADL_ODN_PARAMETER_FAN_CURVE_SPEED_1, + ADL_ODN_PARAMETER_FAN_CURVE_TEMPERATURE_2, + ADL_ODN_PARAMETER_FAN_CURVE_SPEED_2, + ADL_ODN_PARAMETER_FAN_CURVE_TEMPERATURE_3, + ADL_ODN_PARAMETER_FAN_CURVE_SPEED_3, + ADL_ODN_PARAMETER_FAN_CURVE_TEMPERATURE_4, + ADL_ODN_PARAMETER_FAN_CURVE_SPEED_4, + ADL_ODN_PARAMETER_FAN_CURVE_TEMPERATURE_5, + ADL_ODN_PARAMETER_FAN_CURVE_SPEED_5, + ADL_ODN_POWERGAUGE, + ODN_COUNT + +} ; + +//OD8 Capability features bits +enum ADLOD8FeatureControl +{ + ADL_OD8_GFXCLK_LIMITS = 1 << 0, + ADL_OD8_GFXCLK_CURVE = 1 << 1, + ADL_OD8_UCLK_MAX = 1 << 2, + ADL_OD8_POWER_LIMIT = 1 << 3, + ADL_OD8_ACOUSTIC_LIMIT_SCLK = 1 << 4, //FanMaximumRpm + ADL_OD8_FAN_SPEED_MIN = 1 << 5, //FanMinimumPwm + ADL_OD8_TEMPERATURE_FAN = 1 << 6, //FanTargetTemperature + ADL_OD8_TEMPERATURE_SYSTEM = 1 << 7, //MaxOpTemp + ADL_OD8_MEMORY_TIMING_TUNE = 1 << 8, + ADL_OD8_FAN_ZERO_RPM_CONTROL = 1 << 9 , + ADL_OD8_AUTO_UV_ENGINE = 1 << 10, //Auto under voltage + ADL_OD8_AUTO_OC_ENGINE = 1 << 11, //Auto overclock engine + ADL_OD8_AUTO_OC_MEMORY = 1 << 12, //Auto overclock memory + ADL_OD8_FAN_CURVE = 1 << 13, //Fan curve + ADL_OD8_WS_AUTO_FAN_ACOUSTIC_LIMIT = 1 << 14, //Workstation Manual Fan controller + ADL_OD8_POWER_GAUGE = 1 << 15 //Power Gauge +}; + + +typedef enum _ADLOD8SettingId +{ + OD8_GFXCLK_FMAX = 0, + OD8_GFXCLK_FMIN, + OD8_GFXCLK_FREQ1, + OD8_GFXCLK_VOLTAGE1, + OD8_GFXCLK_FREQ2, + OD8_GFXCLK_VOLTAGE2, + OD8_GFXCLK_FREQ3, + OD8_GFXCLK_VOLTAGE3, + OD8_UCLK_FMAX, + OD8_POWER_PERCENTAGE, + OD8_FAN_MIN_SPEED, + OD8_FAN_ACOUSTIC_LIMIT, + OD8_FAN_TARGET_TEMP, + OD8_OPERATING_TEMP_MAX, + OD8_AC_TIMING, + OD8_FAN_ZERORPM_CONTROL, + OD8_AUTO_UV_ENGINE_CONTROL, + OD8_AUTO_OC_ENGINE_CONTROL, + OD8_AUTO_OC_MEMORY_CONTROL, + OD8_FAN_CURVE_TEMPERATURE_1, + OD8_FAN_CURVE_SPEED_1, + OD8_FAN_CURVE_TEMPERATURE_2, + OD8_FAN_CURVE_SPEED_2, + OD8_FAN_CURVE_TEMPERATURE_3, + OD8_FAN_CURVE_SPEED_3, + OD8_FAN_CURVE_TEMPERATURE_4, + OD8_FAN_CURVE_SPEED_4, + OD8_FAN_CURVE_TEMPERATURE_5, + OD8_FAN_CURVE_SPEED_5, + OD8_WS_FAN_AUTO_FAN_ACOUSTIC_LIMIT, + OD8_POWER_GAUGE, //Starting from this is new features with new capabilities and new interface for limits. + OD8_COUNT +} ADLOD8SettingId; + + +//Define Performance Metrics Log max sensors number +#define ADL_PMLOG_MAX_SENSORS 256 + +typedef enum _ADLSensorType +{ + SENSOR_MAXTYPES = 0, + PMLOG_CLK_GFXCLK = 1, + PMLOG_CLK_MEMCLK = 2, + PMLOG_CLK_SOCCLK = 3, + PMLOG_CLK_UVDCLK1 = 4, + PMLOG_CLK_UVDCLK2 = 5, + PMLOG_CLK_VCECLK = 6, + PMLOG_CLK_VCNCLK = 7, + PMLOG_TEMPERATURE_EDGE = 8, + PMLOG_TEMPERATURE_MEM = 9, + PMLOG_TEMPERATURE_VRVDDC = 10, + PMLOG_TEMPERATURE_VRMVDD = 11, + PMLOG_TEMPERATURE_LIQUID = 12, + PMLOG_TEMPERATURE_PLX = 13, + PMLOG_FAN_RPM = 14, + PMLOG_FAN_PERCENTAGE = 15, + PMLOG_SOC_VOLTAGE = 16, + PMLOG_SOC_POWER = 17, + PMLOG_SOC_CURRENT = 18, + PMLOG_INFO_ACTIVITY_GFX = 19, + PMLOG_INFO_ACTIVITY_MEM = 20, + PMLOG_GFX_VOLTAGE = 21, + PMLOG_MEM_VOLTAGE = 22, + PMLOG_ASIC_POWER = 23, + PMLOG_TEMPERATURE_VRSOC = 24, + PMLOG_TEMPERATURE_VRMVDD0 = 25, + PMLOG_TEMPERATURE_VRMVDD1 = 26, + PMLOG_TEMPERATURE_HOTSPOT = 27, + PMLOG_TEMPERATURE_GFX = 28, + PMLOG_TEMPERATURE_SOC = 29, + PMLOG_GFX_POWER = 30, + PMLOG_GFX_CURRENT = 31, + PMLOG_TEMPERATURE_CPU = 32, + PMLOG_CPU_POWER = 33, + PMLOG_CLK_CPUCLK = 34, + PMLOG_THROTTLER_STATUS = 35, + PMLOG_CLK_VCN1CLK1 = 36, + PMLOG_CLK_VCN1CLK2 = 37, + PMLOG_SMART_POWERSHIFT_CPU = 38, + PMLOG_SMART_POWERSHIFT_DGPU = 39, + PMLOG_MAX_SENSORS_REAL +} ADLSensorType; + + +//Throttle Status +typedef enum _ADL_THROTTLE_NOTIFICATION +{ + ADL_PMLOG_THROTTLE_POWER = 1 << 0, + ADL_PMLOG_THROTTLE_THERMAL = 1 << 1, + ADL_PMLOG_THROTTLE_CURRENT = 1 << 2, +} ADL_THROTTLE_NOTIFICATION; + +typedef enum _ADL_PMLOG_SENSORS +{ + ADL_SENSOR_MAXTYPES = 0, + ADL_PMLOG_CLK_GFXCLK = 1, + ADL_PMLOG_CLK_MEMCLK = 2, + ADL_PMLOG_CLK_SOCCLK = 3, + ADL_PMLOG_CLK_UVDCLK1 = 4, + ADL_PMLOG_CLK_UVDCLK2 = 5, + ADL_PMLOG_CLK_VCECLK = 6, + ADL_PMLOG_CLK_VCNCLK = 7, + ADL_PMLOG_TEMPERATURE_EDGE = 8, + ADL_PMLOG_TEMPERATURE_MEM = 9, + ADL_PMLOG_TEMPERATURE_VRVDDC = 10, + ADL_PMLOG_TEMPERATURE_VRMVDD = 11, + ADL_PMLOG_TEMPERATURE_LIQUID = 12, + ADL_PMLOG_TEMPERATURE_PLX = 13, + ADL_PMLOG_FAN_RPM = 14, + ADL_PMLOG_FAN_PERCENTAGE = 15, + ADL_PMLOG_SOC_VOLTAGE = 16, + ADL_PMLOG_SOC_POWER = 17, + ADL_PMLOG_SOC_CURRENT = 18, + ADL_PMLOG_INFO_ACTIVITY_GFX = 19, + ADL_PMLOG_INFO_ACTIVITY_MEM = 20, + ADL_PMLOG_GFX_VOLTAGE = 21, + ADL_PMLOG_MEM_VOLTAGE = 22, + ADL_PMLOG_ASIC_POWER = 23, + ADL_PMLOG_TEMPERATURE_VRSOC = 24, + ADL_PMLOG_TEMPERATURE_VRMVDD0 = 25, + ADL_PMLOG_TEMPERATURE_VRMVDD1 = 26, + ADL_PMLOG_TEMPERATURE_HOTSPOT = 27, + ADL_PMLOG_TEMPERATURE_GFX = 28, + ADL_PMLOG_TEMPERATURE_SOC = 29, + ADL_PMLOG_GFX_POWER = 30, + ADL_PMLOG_GFX_CURRENT = 31, + ADL_PMLOG_TEMPERATURE_CPU = 32, + ADL_PMLOG_CPU_POWER = 33, + ADL_PMLOG_CLK_CPUCLK = 34, + ADL_PMLOG_THROTTLER_STATUS = 35, + ADL_PMLOG_CLK_VCN1CLK1 = 36, + ADL_PMLOG_CLK_VCN1CLK2 = 37, + ADL_PMLOG_SMART_POWERSHIFT_CPU = 38, + ADL_PMLOG_SMART_POWERSHIFT_DGPU = 39 +} ADL_PMLOG_SENSORS; + +/// \defgroup define_ecc_mode_states +/// These defines the ECC(Error Correction Code) state. It is used by \ref ADL_Workstation_ECC_Get,ADL_Workstation_ECC_Set +// @{ +/// Error Correction is OFF. +#define ECC_MODE_OFF 0 +/// Error Correction is ECCV2. +#define ECC_MODE_ON 2 +/// Error Correction is HBM. +#define ECC_MODE_HBM 3 +// @} + +/// \defgroup define_board_layout_flags +/// These defines are the board layout flags state which indicates what are the valid properties of \ref ADLBoardLayoutInfo . It is used by \ref ADL_Adapter_BoardLayout_Get +// @{ +/// Indicates the number of slots is valid. +#define ADL_BLAYOUT_VALID_NUMBER_OF_SLOTS 0x1 +/// Indicates the slot sizes are valid. Size of the slot consists of the length and width. +#define ADL_BLAYOUT_VALID_SLOT_SIZES 0x2 +/// Indicates the connector offsets are valid. +#define ADL_BLAYOUT_VALID_CONNECTOR_OFFSETS 0x4 +/// Indicates the connector lengths is valid. +#define ADL_BLAYOUT_VALID_CONNECTOR_LENGTHS 0x8 +// @} + +/// \defgroup define_max_constants +/// These defines are the maximum value constants. +// @{ +/// Indicates the Maximum supported slots on board. +#define ADL_ADAPTER_MAX_SLOTS 4 +/// Indicates the Maximum supported connectors on slot. +#define ADL_ADAPTER_MAX_CONNECTORS 10 +/// Indicates the Maximum supported properties of connection +#define ADL_MAX_CONNECTION_TYPES 32 +/// Indicates the Maximum relative address link count. +#define ADL_MAX_RELATIVE_ADDRESS_LINK_COUNT 15 +/// Indicates the Maximum size of EDID data block size +#define ADL_MAX_DISPLAY_EDID_DATA_SIZE 1024 +/// Indicates the Maximum count of Error Records. +#define ADL_MAX_ERROR_RECORDS_COUNT 256 +/// Indicates the maximum number of power states supported +#define ADL_MAX_POWER_POLICY 6 +// @} + +/// \defgroup define_connection_types +/// These defines are the connection types constants which indicates what are the valid connection type of given connector. It is used by \ref ADL_Adapter_SupportedConnections_Get +// @{ +/// Indicates the VGA connection type is valid. +#define ADL_CONNECTION_TYPE_VGA 0 +/// Indicates the DVI_I connection type is valid. +#define ADL_CONNECTION_TYPE_DVI 1 +/// Indicates the DVI_SL connection type is valid. +#define ADL_CONNECTION_TYPE_DVI_SL 2 +/// Indicates the HDMI connection type is valid. +#define ADL_CONNECTION_TYPE_HDMI 3 +/// Indicates the DISPLAY PORT connection type is valid. +#define ADL_CONNECTION_TYPE_DISPLAY_PORT 4 +/// Indicates the Active dongle DP->DVI(single link) connection type is valid. +#define ADL_CONNECTION_TYPE_ACTIVE_DONGLE_DP_DVI_SL 5 +/// Indicates the Active dongle DP->DVI(double link) connection type is valid. +#define ADL_CONNECTION_TYPE_ACTIVE_DONGLE_DP_DVI_DL 6 +/// Indicates the Active dongle DP->HDMI connection type is valid. +#define ADL_CONNECTION_TYPE_ACTIVE_DONGLE_DP_HDMI 7 +/// Indicates the Active dongle DP->VGA connection type is valid. +#define ADL_CONNECTION_TYPE_ACTIVE_DONGLE_DP_VGA 8 +/// Indicates the Passive dongle DP->HDMI connection type is valid. +#define ADL_CONNECTION_TYPE_PASSIVE_DONGLE_DP_HDMI 9 +/// Indicates the Active dongle DP->VGA connection type is valid. +#define ADL_CONNECTION_TYPE_PASSIVE_DONGLE_DP_DVI 10 +/// Indicates the MST type is valid. +#define ADL_CONNECTION_TYPE_MST 11 +/// Indicates the active dongle, all types. +#define ADL_CONNECTION_TYPE_ACTIVE_DONGLE 12 +/// Indicates the Virtual Connection Type. +#define ADL_CONNECTION_TYPE_VIRTUAL 13 +/// Macros for generating bitmask from index. +#define ADL_CONNECTION_BITMAST_FROM_INDEX(index) (1 << index) +// @} + +/// \defgroup define_connection_properties +/// These defines are the connection properties which indicates what are the valid properties of given connection type. It is used by \ref ADL_Adapter_SupportedConnections_Get +// @{ +/// Indicates the property Bitrate is valid. +#define ADL_CONNECTION_PROPERTY_BITRATE 0x1 +/// Indicates the property number of lanes is valid. +#define ADL_CONNECTION_PROPERTY_NUMBER_OF_LANES 0x2 +/// Indicates the property 3D caps is valid. +#define ADL_CONNECTION_PROPERTY_3DCAPS 0x4 +/// Indicates the property output bandwidth is valid. +#define ADL_CONNECTION_PROPERTY_OUTPUT_BANDWIDTH 0x8 +/// Indicates the property colordepth is valid. +#define ADL_CONNECTION_PROPERTY_COLORDEPTH 0x10 +// @} + +/// \defgroup define_lanecount_constants +/// These defines are the Lane count constants which will be used in DP & etc. +// @{ +/// Indicates if lane count is unknown +#define ADL_LANECOUNT_UNKNOWN 0 +/// Indicates if lane count is 1 +#define ADL_LANECOUNT_ONE 1 +/// Indicates if lane count is 2 +#define ADL_LANECOUNT_TWO 2 +/// Indicates if lane count is 4 +#define ADL_LANECOUNT_FOUR 4 +/// Indicates if lane count is 8 +#define ADL_LANECOUNT_EIGHT 8 +/// Indicates default value of lane count +#define ADL_LANECOUNT_DEF ADL_LANECOUNT_FOUR +// @} + +/// \defgroup define_linkrate_constants +/// These defines are the link rate constants which will be used in DP & etc. +// @{ +/// Indicates if link rate is unknown +#define ADL_LINK_BITRATE_UNKNOWN 0 +/// Indicates if link rate is 1.62Ghz +#define ADL_LINK_BITRATE_1_62_GHZ 0x06 +/// Indicates if link rate is 2.7Ghz +#define ADL_LINK_BITRATE_2_7_GHZ 0x0A +/// Indicates if link rate is 5.4Ghz +#define ADL_LINK_BITRATE_5_4_GHZ 0x14 + +/// Indicates if link rate is 8.1Ghz +#define ADL_LINK_BITRATE_8_1_GHZ 0x1E +/// Indicates default value of link rate +#define ADL_LINK_BITRATE_DEF ADL_LINK_BITRATE_2_7_GHZ +// @} + +/// \defgroup define_colordepth_constants +/// These defines are the color depth constants which will be used in DP & etc. +// @{ +#define ADL_CONNPROP_S3D_ALTERNATE_TO_FRAME_PACK 0x00000001 +// @} + + +/// \defgroup define_colordepth_constants +/// These defines are the color depth constants which will be used in DP & etc. +// @{ +/// Indicates if color depth is unknown +#define ADL_COLORDEPTH_UNKNOWN 0 +/// Indicates if color depth is 666 +#define ADL_COLORDEPTH_666 1 +/// Indicates if color depth is 888 +#define ADL_COLORDEPTH_888 2 +/// Indicates if color depth is 101010 +#define ADL_COLORDEPTH_101010 3 +/// Indicates if color depth is 121212 +#define ADL_COLORDEPTH_121212 4 +/// Indicates if color depth is 141414 +#define ADL_COLORDEPTH_141414 5 +/// Indicates if color depth is 161616 +#define ADL_COLORDEPTH_161616 6 +/// Indicates default value of color depth +#define ADL_COLOR_DEPTH_DEF ADL_COLORDEPTH_888 +// @} + + +/// \defgroup define_emulation_status +/// These defines are the status of emulation +// @{ +/// Indicates if real device is connected. +#define ADL_EMUL_STATUS_REAL_DEVICE_CONNECTED 0x1 +/// Indicates if emulated device is presented. +#define ADL_EMUL_STATUS_EMULATED_DEVICE_PRESENT 0x2 +/// Indicates if emulated device is used. +#define ADL_EMUL_STATUS_EMULATED_DEVICE_USED 0x4 +/// In case when last active real/emulated device used (when persistence is enabled but no emulation enforced then persistence will use last connected/emulated device). +#define ADL_EMUL_STATUS_LAST_ACTIVE_DEVICE_USED 0x8 +// @} + +/// \defgroup define_emulation_mode +/// These defines are the modes of emulation +// @{ +/// Indicates if no emulation is used +#define ADL_EMUL_MODE_OFF 0 +/// Indicates if emulation is used when display connected +#define ADL_EMUL_MODE_ON_CONNECTED 1 +/// Indicates if emulation is used when display dis connected +#define ADL_EMUL_MODE_ON_DISCONNECTED 2 +/// Indicates if emulation is used always +#define ADL_EMUL_MODE_ALWAYS 3 +// @} + +/// \defgroup define_emulation_query +/// These defines are the modes of emulation +// @{ +/// Indicates Data from real device +#define ADL_QUERY_REAL_DATA 0 +/// Indicates Emulated data +#define ADL_QUERY_EMULATED_DATA 1 +/// Indicates Data currently in use +#define ADL_QUERY_CURRENT_DATA 2 +// @} + +/// \defgroup define_persistence_state +/// These defines are the states of persistence +// @{ +/// Indicates persistence is disabled +#define ADL_EDID_PERSISTANCE_DISABLED 0 +/// Indicates persistence is enabled +#define ADL_EDID_PERSISTANCE_ENABLED 1 +// @} + +/// \defgroup define_connector_types Connector Type +/// defines for ADLConnectorInfo.iType +// @{ +/// Indicates unknown Connector type +#define ADL_CONNECTOR_TYPE_UNKNOWN 0 +/// Indicates VGA Connector type +#define ADL_CONNECTOR_TYPE_VGA 1 +/// Indicates DVI-D Connector type +#define ADL_CONNECTOR_TYPE_DVI_D 2 +/// Indicates DVI-I Connector type +#define ADL_CONNECTOR_TYPE_DVI_I 3 +/// Indicates Active Dongle-NA Connector type +#define ADL_CONNECTOR_TYPE_ATICVDONGLE_NA 4 +/// Indicates Active Dongle-JP Connector type +#define ADL_CONNECTOR_TYPE_ATICVDONGLE_JP 5 +/// Indicates Active Dongle-NONI2C Connector type +#define ADL_CONNECTOR_TYPE_ATICVDONGLE_NONI2C 6 +/// Indicates Active Dongle-NONI2C-D Connector type +#define ADL_CONNECTOR_TYPE_ATICVDONGLE_NONI2C_D 7 +/// Indicates HDMI-Type A Connector type +#define ADL_CONNECTOR_TYPE_HDMI_TYPE_A 8 +/// Indicates HDMI-Type B Connector type +#define ADL_CONNECTOR_TYPE_HDMI_TYPE_B 9 +/// Indicates Display port Connector type +#define ADL_CONNECTOR_TYPE_DISPLAYPORT 10 +/// Indicates EDP Connector type +#define ADL_CONNECTOR_TYPE_EDP 11 +/// Indicates MiniDP Connector type +#define ADL_CONNECTOR_TYPE_MINI_DISPLAYPORT 12 +/// Indicates Virtual Connector type +#define ADL_CONNECTOR_TYPE_VIRTUAL 13 +// @} + +/// \defgroup define_freesync_usecase +/// These defines are to specify use cases in which FreeSync should be enabled +/// They are a bit mask. To specify FreeSync for more than one use case, the input value +/// should be set to include multiple bits set +// @{ +/// Indicates FreeSync is enabled for Static Screen case +#define ADL_FREESYNC_USECASE_STATIC 0x1 +/// Indicates FreeSync is enabled for Video use case +#define ADL_FREESYNC_USECASE_VIDEO 0x2 +/// Indicates FreeSync is enabled for Gaming use case +#define ADL_FREESYNC_USECASE_GAMING 0x4 +// @} + +/// \defgroup define_freesync_caps +/// These defines are used to retrieve FreeSync display capabilities. +/// GPU support flag also indicates whether the display is +/// connected to a GPU that actually supports FreeSync +// @{ +#define ADL_FREESYNC_CAP_SUPPORTED (1 << 0) +#define ADL_FREESYNC_CAP_GPUSUPPORTED (1 << 1) +#define ADL_FREESYNC_CAP_DISPLAYSUPPORTED (1 << 2) +#define ADL_FREESYNC_CAP_CURRENTMODESUPPORTED (1 << 3) +#define ADL_FREESYNC_CAP_NOCFXORCFXSUPPORTED (1 << 4) +#define ADL_FREESYNC_CAP_NOGENLOCKORGENLOCKSUPPORTED (1 << 5) +#define ADL_FREESYNC_CAP_BORDERLESSWINDOWSUPPORTED (1 << 6) +// @} + + +/// \defgroup define_MST_CommandLine_execute +// @{ +/// Indicates the MST command line for branch message if the bit is set. Otherwise, it is display message +#define ADL_MST_COMMANDLINE_PATH_MSG 0x1 +/// Indicates the MST command line to send message in broadcast way it the bit is set +#define ADL_MST_COMMANDLINE_BROADCAST 0x2 + +// @} + + +/// \defgroup define_Adapter_CloneTypes_Get +// @{ +/// Indicates there is crossGPU clone with non-AMD dispalys +#define ADL_CROSSGPUDISPLAYCLONE_AMD_WITH_NONAMD 0x1 +/// Indicates there is crossGPU clone +#define ADL_CROSSGPUDISPLAYCLONE 0x2 + +// @} + +/// \defgroup define_D3DKMT_HANDLE +// @{ +/// Handle can be used to create Device Handle when using CreateDevice() +typedef unsigned int ADL_D3DKMT_HANDLE; +// @} + + +// End Bracket for Constants and Definitions. Add new groups ABOVE this line! + +// @} + + +typedef enum _ADL_RAS_ERROR_INJECTION_MODE +{ + ADL_RAS_ERROR_INJECTION_MODE_SINGLE = 1, + ADL_RAS_ERROR_INJECTION_MODE_MULTIPLE = 2 +}ADL_RAS_ERROR_INJECTION_MODE; + + +typedef enum _ADL_RAS_BLOCK_ID +{ + ADL_RAS_BLOCK_ID_UMC = 0, + ADL_RAS_BLOCK_ID_SDMA, + ADL_RAS_BLOCK_ID_GFX_HUB, + ADL_RAS_BLOCK_ID_MMHUB, + ADL_RAS_BLOCK_ID_ATHUB, + ADL_RAS_BLOCK_ID_PCIE_BIF, + ADL_RAS_BLOCK_ID_HDP, + ADL_RAS_BLOCK_ID_XGMI_WAFL, + ADL_RAS_BLOCK_ID_DF, + ADL_RAS_BLOCK_ID_SMN, + ADL_RAS_BLOCK_ID_SEM, + ADL_RAS_BLOCK_ID_MP0, + ADL_RAS_BLOCK_ID_MP1, + ADL_RAS_BLOCK_ID_FUSE +}ADL_RAS_BLOCK_ID; + +typedef enum _ADL_MEM_SUB_BLOCK_ID +{ + ADL_RAS__UMC_HBM = 0, + ADL_RAS__UMC_SRAM = 1 +}ADL_MEM_SUB_BLOCK_ID; + +typedef enum _ADL_RAS_ERROR_TYPE +{ + ADL_RAS_ERROR__NONE = 0, + ADL_RAS_ERROR__PARITY = 1, + ADL_RAS_ERROR__SINGLE_CORRECTABLE = 2, + ADL_RAS_ERROR__PARITY_SINGLE_CORRECTABLE = 3, + ADL_RAS_ERROR__MULTI_UNCORRECTABLE = 4, + ADL_RAS_ERROR__PARITY_MULTI_UNCORRECTABLE = 5, + ADL_RAS_ERROR__SINGLE_CORRECTABLE_MULTI_UNCORRECTABLE = 6, + ADL_RAS_ERROR__PARITY_SINGLE_CORRECTABLE_MULTI_UNCORRECTABLE = 7, + ADL_RAS_ERROR__POISON = 8, + ADL_RAS_ERROR__PARITY_POISON = 9, + ADL_RAS_ERROR__SINGLE_CORRECTABLE_POISON = 10, + ADL_RAS_ERROR__PARITY_SINGLE_CORRECTABLE_POISON = 11, + ADL_RAS_ERROR__MULTI_UNCORRECTABLE_POISON = 12, + ADL_RAS_ERROR__PARITY_MULTI_UNCORRECTABLE_POISON = 13, + ADL_RAS_ERROR__SINGLE_CORRECTABLE_MULTI_UNCORRECTABLE_POISON = 14, + ADL_RAS_ERROR__PARITY_SINGLE_CORRECTABLE_MULTI_UNCORRECTABLE_POISON = 15 +}ADL_RAS_ERROR_TYPE; + +typedef enum _ADL_RAS_INJECTION_METHOD +{ + ADL_RAS_ERROR__UMC_METH_COHERENT = 0, + ADL_RAS_ERROR__UMC_METH_SINGLE_SHOT = 1, + ADL_RAS_ERROR__UMC_METH_PERSISTENT = 2, + ADL_RAS_ERROR__UMC_METH_PERSISTENT_DISABLE = 3 +}ADL_RAS_INJECTION_METHOD; + +// Driver event types +typedef enum _ADL_DRIVER_EVENT_TYPE +{ + ADL_EVENT_ID_AUTO_FEATURE_COMPLETED = 30, + ADL_EVENT_ID_FEATURE_AVAILABILITY = 31, + +} ADL_DRIVER_EVENT_TYPE; + + +//UIFeature Ids +typedef enum _ADL_UIFEATURES_GROUP +{ + ADL_UIFEATURES_GROUP_DVR = 0, + ADL_UIFEATURES_GROUP_TURBOSYNC = 1, + ADL_UIFEATURES_GROUP_FRAMEMETRICSMONITOR = 2, + ADL_UIFEATURES_GROUP_FRTC = 3, + ADL_UIFEATURES_GROUP_XVISION = 4, + ADL_UIFEATURES_GROUP_BLOCKCHAIN = 5, + ADL_UIFEATURES_GROUP_GAMEINTELLIGENCE = 6, + ADL_UIFEATURES_GROUP_CHILL = 7, + ADL_UIFEATURES_GROUP_DELAG = 8, + ADL_UIFEATURES_GROUP_BOOST = 9, + ADL_UIFEATURES_GROUP_USU = 10, + ADL_UIFEATURES_GROUP_XGMI = 11 +}ADL_UIFEATURES_GROUP; + +#endif /* ADL_DEFINES_H_ */ + + diff --git a/src/3rdparty/adl/adl_sdk.h b/src/3rdparty/adl/adl_sdk.h new file mode 100644 index 00000000..8658f29a --- /dev/null +++ b/src/3rdparty/adl/adl_sdk.h @@ -0,0 +1,44 @@ +// +// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. +// +// MIT LICENSE: +// 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. + +/// \file adl_sdk.h +/// \brief Contains the definition of the Memory Allocation Callback.\n Included in ADL SDK +/// +/// \n\n +/// This file contains the definition of the Memory Allocation Callback.\n +/// It also includes definitions of the respective structures and constants.\n +/// This is the only header file to be included in a C/C++ project using ADL + +#ifndef ADL_SDK_H_ +#define ADL_SDK_H_ + +#include "adl_structures.h" + +#if defined (LINUX) +#define __stdcall +#endif /* (LINUX) */ + +/// Memory Allocation Call back +typedef void* ( __stdcall *ADL_MAIN_MALLOC_CALLBACK )( int ); + + +#endif /* ADL_SDK_H_ */ diff --git a/src/3rdparty/adl/adl_structures.h b/src/3rdparty/adl/adl_structures.h new file mode 100644 index 00000000..f05a1d99 --- /dev/null +++ b/src/3rdparty/adl/adl_structures.h @@ -0,0 +1,3440 @@ +// +// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. +// +// MIT LICENSE: +// 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. + +/// \file adl_structures.h +///\brief This file contains the structure declarations that are used by the public ADL interfaces for \ALL platforms.\n Included in ADL SDK +/// +/// All data structures used in AMD Display Library (ADL) public interfaces should be defined in this header file. +/// + +#ifndef ADL_STRUCTURES_H_ +#define ADL_STRUCTURES_H_ + +#include "adl_defines.h" + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the graphics adapter. +/// +/// This structure is used to store various information about the graphics adapter. This +/// information can be returned to the user. Alternatively, it can be used to access various driver calls to set +/// or fetch various settings upon the user's request. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct AdapterInfo +{ +/// \ALL_STRUCT_MEM + +/// Size of the structure. + int iSize; +/// The ADL index handle. One GPU may be associated with one or two index handles + int iAdapterIndex; +/// The unique device ID associated with this adapter. + char strUDID[ADL_MAX_PATH]; +/// The BUS number associated with this adapter. + int iBusNumber; +/// The driver number associated with this adapter. + int iDeviceNumber; +/// The function number. + int iFunctionNumber; +/// The vendor ID associated with this adapter. + int iVendorID; +/// Adapter name. + char strAdapterName[ADL_MAX_PATH]; +/// Display name. For example, "\\\\Display0" for Windows or ":0:0" for Linux. + char strDisplayName[ADL_MAX_PATH]; +/// Present or not; 1 if present and 0 if not present.It the logical adapter is present, the display name such as \\\\.\\Display1 can be found from OS + int iPresent; + +#if defined (_WIN32) || defined (_WIN64) +/// \WIN_STRUCT_MEM + +/// Exist or not; 1 is exist and 0 is not present. + int iExist; +/// Driver registry path. + char strDriverPath[ADL_MAX_PATH]; +/// Driver registry path Ext for. + char strDriverPathExt[ADL_MAX_PATH]; +/// PNP string from Windows. + char strPNPString[ADL_MAX_PATH]; +/// It is generated from EnumDisplayDevices. + int iOSDisplayIndex; +#endif /* (_WIN32) || (_WIN64) */ + +#if defined (LINUX) +/// \LNX_STRUCT_MEM + +/// Internal X screen number from GPUMapInfo (DEPRICATED use XScreenInfo) + int iXScreenNum; +/// Internal driver index from GPUMapInfo + int iDrvIndex; +/// \deprecated Internal x config file screen identifier name. Use XScreenInfo instead. + char strXScreenConfigName[ADL_MAX_PATH]; + +#endif /* (LINUX) */ +} AdapterInfo, *LPAdapterInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the Linux X screen information. +/// +/// This structure is used to store the current screen number and xorg.conf ID name assoicated with an adapter index. +/// This structure is updated during ADL_Main_Control_Refresh or ADL_ScreenInfo_Update. +/// Note: This structure should be used in place of iXScreenNum and strXScreenConfigName in AdapterInfo as they will be +/// deprecated. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +#if defined (LINUX) +typedef struct XScreenInfo +{ +/// Internal X screen number from GPUMapInfo. + int iXScreenNum; +/// Internal x config file screen identifier name. + char strXScreenConfigName[ADL_MAX_PATH]; +} XScreenInfo, *LPXScreenInfo; +#endif /* (LINUX) */ + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the ASIC memory. +/// +/// This structure is used to store various information about the ASIC memory. This +/// information can be returned to the user. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLMemoryInfo +{ +/// Memory size in bytes. + long long iMemorySize; +/// Memory type in string. + char strMemoryType[ADL_MAX_PATH]; +/// Memory bandwidth in Mbytes/s. + long long iMemoryBandwidth; +} ADLMemoryInfo, *LPADLMemoryInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about memory required by type +/// +/// This structure is returned by ADL_Adapter_ConfigMemory_Get, which given a desktop and display configuration +/// will return the Memory used. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLMemoryRequired +{ + long long iMemoryReq; /// Memory in bytes required + int iType; /// Type of Memory \ref define_adl_validmemoryrequiredfields + int iDisplayFeatureValue; /// Display features \ref define_adl_visiblememoryfeatures that are using this type of memory +} ADLMemoryRequired, *LPADLMemoryRequired; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the features associated with a display +/// +/// This structure is a parameter to ADL_Adapter_ConfigMemory_Get, which given a desktop and display configuration +/// will return the Memory used. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLMemoryDisplayFeatures +{ + int iDisplayIndex; /// ADL Display index + int iDisplayFeatureValue; /// features that the display is using \ref define_adl_visiblememoryfeatures +} ADLMemoryDisplayFeatures, *LPADLMemoryDisplayFeatures; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing DDC information. +/// +/// This structure is used to store various DDC information that can be returned to the user. +/// Note that all fields of type int are actually defined as unsigned int types within the driver. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDDCInfo +{ +/// Size of the structure + int ulSize; +/// Indicates whether the attached display supports DDC. If this field is zero on return, no other DDC information fields will be used. + int ulSupportsDDC; +/// Returns the manufacturer ID of the display device. Should be zeroed if this information is not available. + int ulManufacturerID; +/// Returns the product ID of the display device. Should be zeroed if this information is not available. + int ulProductID; +/// Returns the name of the display device. Should be zeroed if this information is not available. + char cDisplayName[ADL_MAX_DISPLAY_NAME]; +/// Returns the maximum Horizontal supported resolution. Should be zeroed if this information is not available. + int ulMaxHResolution; +/// Returns the maximum Vertical supported resolution. Should be zeroed if this information is not available. + int ulMaxVResolution; +/// Returns the maximum supported refresh rate. Should be zeroed if this information is not available. + int ulMaxRefresh; +/// Returns the display device preferred timing mode's horizontal resolution. + int ulPTMCx; +/// Returns the display device preferred timing mode's vertical resolution. + int ulPTMCy; +/// Returns the display device preferred timing mode's refresh rate. + int ulPTMRefreshRate; +/// Return EDID flags. + int ulDDCInfoFlag; +} ADLDDCInfo, *LPADLDDCInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing DDC information. +/// +/// This structure is used to store various DDC information that can be returned to the user. +/// Note that all fields of type int are actually defined as unsigned int types within the driver. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDDCInfo2 +{ +/// Size of the structure + int ulSize; +/// Indicates whether the attached display supports DDC. If this field is zero on return, no other DDC +/// information fields will be used. + int ulSupportsDDC; +/// Returns the manufacturer ID of the display device. Should be zeroed if this information is not available. + int ulManufacturerID; +/// Returns the product ID of the display device. Should be zeroed if this information is not available. + int ulProductID; +/// Returns the name of the display device. Should be zeroed if this information is not available. + char cDisplayName[ADL_MAX_DISPLAY_NAME]; +/// Returns the maximum Horizontal supported resolution. Should be zeroed if this information is not available. + int ulMaxHResolution; +/// Returns the maximum Vertical supported resolution. Should be zeroed if this information is not available. + int ulMaxVResolution; +/// Returns the maximum supported refresh rate. Should be zeroed if this information is not available. + int ulMaxRefresh; +/// Returns the display device preferred timing mode's horizontal resolution. + int ulPTMCx; +/// Returns the display device preferred timing mode's vertical resolution. + int ulPTMCy; +/// Returns the display device preferred timing mode's refresh rate. + int ulPTMRefreshRate; +/// Return EDID flags. + int ulDDCInfoFlag; +/// Returns 1 if the display supported packed pixel, 0 otherwise + int bPackedPixelSupported; +/// Returns the Pixel formats the display supports \ref define_ddcinfo_pixelformats + int iPanelPixelFormat; +/// Return EDID serial ID. + int ulSerialID; +/// Return minimum monitor luminance data + int ulMinLuminanceData; +/// Return average monitor luminance data + int ulAvgLuminanceData; +/// Return maximum monitor luminance data + int ulMaxLuminanceData; + +/// Bit vector of supported transfer functions \ref define_source_content_TF + int iSupportedTransferFunction; + +/// Bit vector of supported color spaces \ref define_source_content_CS + int iSupportedColorSpace; + +/// Display Red Chromaticity X coordinate multiplied by 10000 + int iNativeDisplayChromaticityRedX; +/// Display Red Chromaticity Y coordinate multiplied by 10000 + int iNativeDisplayChromaticityRedY; +/// Display Green Chromaticity X coordinate multiplied by 10000 + int iNativeDisplayChromaticityGreenX; +/// Display Green Chromaticity Y coordinate multiplied by 10000 + int iNativeDisplayChromaticityGreenY; +/// Display Blue Chromaticity X coordinate multiplied by 10000 + int iNativeDisplayChromaticityBlueX; +/// Display Blue Chromaticity Y coordinate multiplied by 10000 + int iNativeDisplayChromaticityBlueY; +/// Display White Point X coordinate multiplied by 10000 + int iNativeDisplayChromaticityWhitePointX; +/// Display White Point Y coordinate multiplied by 10000 + int iNativeDisplayChromaticityWhitePointY; +/// Display diffuse screen reflectance 0-1 (100%) in units of 0.01 + int iDiffuseScreenReflectance; +/// Display specular screen reflectance 0-1 (100%) in units of 0.01 + int iSpecularScreenReflectance; +/// Bit vector of supported color spaces \ref define_HDR_support + int iSupportedHDR; +/// Bit vector for freesync flags + int iFreesyncFlags; + +/// Return minimum monitor luminance without dimming data + int ulMinLuminanceNoDimmingData; + + int ulMaxBacklightMaxLuminanceData; + int ulMinBacklightMaxLuminanceData; + int ulMaxBacklightMinLuminanceData; + int ulMinBacklightMinLuminanceData; + + // Reserved for future use + int iReserved[4]; +} ADLDDCInfo2, *LPADLDDCInfo2; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information controller Gamma settings. +/// +/// This structure is used to store the red, green and blue color channel information for the. +/// controller gamma setting. This information is returned by ADL, and it can also be used to +/// set the controller gamma setting. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGamma +{ +/// Red color channel gamma value. + float fRed; +/// Green color channel gamma value. + float fGreen; +/// Blue color channel gamma value. + float fBlue; +} ADLGamma, *LPADLGamma; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about component video custom modes. +/// +/// This structure is used to store the component video custom mode. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLCustomMode +{ +/// Custom mode flags. They are returned by the ADL driver. + int iFlags; +/// Custom mode width. + int iModeWidth; +/// Custom mode height. + int iModeHeight; +/// Custom mode base width. + int iBaseModeWidth; +/// Custom mode base height. + int iBaseModeHeight; +/// Custom mode refresh rate. + int iRefreshRate; +} ADLCustomMode, *LPADLCustomMode; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing Clock information for OD5 calls. +/// +/// This structure is used to retrieve clock information for OD5 calls. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGetClocksOUT +{ + long ulHighCoreClock; + long ulHighMemoryClock; + long ulHighVddc; + long ulCoreMin; + long ulCoreMax; + long ulMemoryMin; + long ulMemoryMax; + long ulActivityPercent; + long ulCurrentCoreClock; + long ulCurrentMemoryClock; + long ulReserved; +} ADLGetClocksOUT; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing HDTV information for display calls. +/// +/// This structure is used to retrieve HDTV information information for display calls. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayConfig +{ +/// Size of the structure + long ulSize; +/// HDTV connector type. + long ulConnectorType; +/// HDTV capabilities. + long ulDeviceData; +/// Overridden HDTV capabilities. + long ulOverridedDeviceData; +/// Reserved field + long ulReserved; +} ADLDisplayConfig; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display device. +/// +/// This structure is used to store display device information +/// such as display index, type, name, connection status, mapped adapter and controller indexes, +/// whether or not multiple VPUs are supported, local display connections or not (through Lasso), etc. +/// This information can be returned to the user. Alternatively, it can be used to access various driver calls to set +/// or fetch various display device related settings upon the user's request. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayID +{ +/// The logical display index belonging to this adapter. + int iDisplayLogicalIndex; + +///\brief The physical display index. +/// For example, display index 2 from adapter 2 can be used by current adapter 1.\n +/// So current adapter may enumerate this adapter as logical display 7 but the physical display +/// index is still 2. + int iDisplayPhysicalIndex; + +/// The persistent logical adapter index for the display. + int iDisplayLogicalAdapterIndex; + +///\brief The persistent physical adapter index for the display. +/// It can be the current adapter or a non-local adapter. \n +/// If this adapter index is different than the current adapter, +/// the Display Non Local flag is set inside DisplayInfoValue. + int iDisplayPhysicalAdapterIndex; +} ADLDisplayID, *LPADLDisplayID; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display device. +/// +/// This structure is used to store various information about the display device. This +/// information can be returned to the user, or used to access various driver calls to set +/// or fetch various display-device-related settings upon the user's request +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayInfo +{ +/// The DisplayID structure + ADLDisplayID displayID; + +///\deprecated The controller index to which the display is mapped.\n Will not be used in the future\n + int iDisplayControllerIndex; + +/// The display's EDID name. + char strDisplayName[ADL_MAX_PATH]; + +/// The display's manufacturer name. + char strDisplayManufacturerName[ADL_MAX_PATH]; + +/// The Display type. For example: CRT, TV, CV, DFP. + int iDisplayType; + +/// The display output type. For example: HDMI, SVIDEO, COMPONMNET VIDEO. + int iDisplayOutputType; + +/// The connector type for the device. + int iDisplayConnector; + +///\brief The bit mask identifies the number of bits ADLDisplayInfo is currently using. \n +/// It will be the sum all the bit definitions in ADL_DISPLAY_DISPLAYINFO_xxx. + int iDisplayInfoMask; + +/// The bit mask identifies the display status. \ref define_displayinfomask + int iDisplayInfoValue; +} ADLDisplayInfo, *LPADLDisplayInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display port MST device. +/// +/// This structure is used to store various MST information about the display port device. This +/// information can be returned to the user, or used to access various driver calls to +/// fetch various display-device-related settings upon the user's request +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayDPMSTInfo +{ + /// The ADLDisplayID structure + ADLDisplayID displayID; + + /// total bandwidth available on the DP connector + int iTotalAvailableBandwidthInMpbs; + /// bandwidth allocated to this display + int iAllocatedBandwidthInMbps; + + // info from DAL DpMstSinkInfo + /// string identifier for the display + char strGlobalUniqueIdentifier[ADL_MAX_PATH]; + + /// The link count of relative address, rad[0] upto rad[linkCount] are valid + int radLinkCount; + /// The physical connector ID, used to identify the physical DP port + int iPhysicalConnectorID; + + /// Relative address, address scheme starts from source side + char rad[ADL_MAX_RAD_LINK_COUNT]; +} ADLDisplayDPMSTInfo, *LPADLDisplayDPMSTInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the display mode definition used per controller. +/// +/// This structure is used to store the display mode definition used per controller. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayMode +{ +/// Vertical resolution (in pixels). + int iPelsHeight; +/// Horizontal resolution (in pixels). + int iPelsWidth; +/// Color depth. + int iBitsPerPel; +/// Refresh rate. + int iDisplayFrequency; +} ADLDisplayMode; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing detailed timing parameters. +/// +/// This structure is used to store the detailed timing parameters. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDetailedTiming +{ +/// Size of the structure. + int iSize; +/// Timing flags. \ref define_detailed_timing_flags + short sTimingFlags; +/// Total width (columns). + short sHTotal; +/// Displayed width. + short sHDisplay; +/// Horizontal sync signal offset. + short sHSyncStart; +/// Horizontal sync signal width. + short sHSyncWidth; +/// Total height (rows). + short sVTotal; +/// Displayed height. + short sVDisplay; +/// Vertical sync signal offset. + short sVSyncStart; +/// Vertical sync signal width. + short sVSyncWidth; +/// Pixel clock value. + short sPixelClock; +/// Overscan right. + short sHOverscanRight; +/// Overscan left. + short sHOverscanLeft; +/// Overscan bottom. + short sVOverscanBottom; +/// Overscan top. + short sVOverscanTop; + short sOverscan8B; + short sOverscanGR; +} ADLDetailedTiming; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing display mode information. +/// +/// This structure is used to store the display mode information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayModeInfo +{ +/// Timing standard of the current mode. \ref define_modetiming_standard + int iTimingStandard; +/// Applicable timing standards for the current mode. + int iPossibleStandard; +/// Refresh rate factor. + int iRefreshRate; +/// Num of pixels in a row. + int iPelsWidth; +/// Num of pixels in a column. + int iPelsHeight; +/// Detailed timing parameters. + ADLDetailedTiming sDetailedTiming; +} ADLDisplayModeInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about display property. +/// +/// This structure is used to store the display property for the current adapter. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayProperty +{ +/// Must be set to sizeof the structure + int iSize; +/// Must be set to \ref ADL_DL_DISPLAYPROPERTY_TYPE_EXPANSIONMODE or \ref ADL_DL_DISPLAYPROPERTY_TYPE_USEUNDERSCANSCALING + int iPropertyType; +/// Get or Set \ref ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_CENTER or \ref ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_FULLSCREEN or \ref ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_ASPECTRATIO or \ref ADL_DL_DISPLAYPROPERTY_TYPE_ITCFLAGENABLE + int iExpansionMode; +/// Display Property supported? 1: Supported, 0: Not supported + int iSupport; +/// Display Property current value + int iCurrent; +/// Display Property Default value + int iDefault; +} ADLDisplayProperty; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Clock. +/// +/// This structure is used to store the clock information for the current adapter +/// such as core clock and memory clock info. +///\nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLClockInfo +{ +/// Core clock in 10 KHz. + int iCoreClock; +/// Memory clock in 10 KHz. + int iMemoryClock; +} ADLClockInfo, *LPADLClockInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about I2C. +/// +/// This structure is used to store the I2C information for the current adapter. +/// This structure is used by the ADL_Display_WriteAndReadI2C() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLI2C +{ +/// Size of the structure + int iSize; +/// Numerical value representing hardware I2C. + int iLine; +/// The 7-bit I2C slave device address, shifted one bit to the left. + int iAddress; +/// The offset of the data from the address. + int iOffset; +/// Read from or write to slave device. \ref ADL_DL_I2C_ACTIONREAD or \ref ADL_DL_I2C_ACTIONWRITE or \ref ADL_DL_I2C_ACTIONREAD_REPEATEDSTART + int iAction; +/// I2C clock speed in KHz. + int iSpeed; +/// A numerical value representing the number of bytes to be sent or received on the I2C bus. + int iDataSize; +/// Address of the characters which are to be sent or received on the I2C bus. + char *pcData; +} ADLI2C; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about EDID data. +/// +/// This structure is used to store the information about EDID data for the adapter. +/// This structure is used by the ADL_Display_EdidData_Get() and ADL_Display_EdidData_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayEDIDData +{ +/// Size of the structure + int iSize; +/// Set to 0 + int iFlag; + /// Size of cEDIDData. Set by ADL_Display_EdidData_Get() upon return + int iEDIDSize; +/// 0, 1 or 2. If set to 3 or above an error ADL_ERR_INVALID_PARAM is generated + int iBlockIndex; +/// EDID data + char cEDIDData[ADL_MAX_EDIDDATA_SIZE]; +/// Reserved + int iReserved[4]; +}ADLDisplayEDIDData; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about input of controller overlay adjustment. +/// +/// This structure is used to store the information about input of controller overlay adjustment for the adapter. +/// This structure is used by the ADL_Display_ControllerOverlayAdjustmentCaps_Get, ADL_Display_ControllerOverlayAdjustmentData_Get, and +/// ADL_Display_ControllerOverlayAdjustmentData_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLControllerOverlayInput +{ +/// Should be set to the sizeof the structure + int iSize; +///\ref ADL_DL_CONTROLLER_OVERLAY_ALPHA or \ref ADL_DL_CONTROLLER_OVERLAY_ALPHAPERPIX + int iOverlayAdjust; +/// Data. + int iValue; +/// Should be 0. + int iReserved; +} ADLControllerOverlayInput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about overlay adjustment. +/// +/// This structure is used to store the information about overlay adjustment for the adapter. +/// This structure is used by the ADLControllerOverlayInfo() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLAdjustmentinfo +{ +/// Default value + int iDefault; +/// Minimum value + int iMin; +/// Maximum Value + int iMax; +/// Step value + int iStep; +} ADLAdjustmentinfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about controller overlay information. +/// +/// This structure is used to store information about controller overlay info for the adapter. +/// This structure is used by the ADL_Display_ControllerOverlayAdjustmentCaps_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLControllerOverlayInfo +{ +/// Should be set to the sizeof the structure + int iSize; +/// Data. + ADLAdjustmentinfo sOverlayInfo; +/// Should be 0. + int iReserved[3]; +} ADLControllerOverlayInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing GL-Sync module information. +/// +/// This structure is used to retrieve GL-Sync module information for +/// Workstation Framelock/Genlock. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGLSyncModuleID +{ +/// Unique GL-Sync module ID. + int iModuleID; +/// GL-Sync GPU port index (to be passed into ADLGLSyncGenlockConfig.lSignalSource and ADLGlSyncPortControl.lSignalSource). + int iGlSyncGPUPort; +/// GL-Sync module firmware version of Boot Sector. + int iFWBootSectorVersion; +/// GL-Sync module firmware version of User Sector. + int iFWUserSectorVersion; +} ADLGLSyncModuleID , *LPADLGLSyncModuleID; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing GL-Sync ports capabilities. +/// +/// This structure is used to retrieve hardware capabilities for the ports of the GL-Sync module +/// for Workstation Framelock/Genlock (such as port type and number of associated LEDs). +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGLSyncPortCaps +{ +/// Port type. Bitfield of ADL_GLSYNC_PORTTYPE_* \ref define_glsync + int iPortType; +/// Number of LEDs associated for this port. + int iNumOfLEDs; +}ADLGLSyncPortCaps, *LPADLGLSyncPortCaps; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing GL-Sync Genlock settings. +/// +/// This structure is used to get and set genlock settings for the GPU ports of the GL-Sync module +/// for Workstation Framelock/Genlock.\n +/// \see define_glsync +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGLSyncGenlockConfig +{ +/// Specifies what fields in this structure are valid \ref define_glsync + int iValidMask; +/// Delay (ms) generating a sync signal. + int iSyncDelay; +/// Vector of framelock control bits. Bitfield of ADL_GLSYNC_FRAMELOCKCNTL_* \ref define_glsync + int iFramelockCntlVector; +/// Source of the sync signal. Either GL_Sync GPU Port index or ADL_GLSYNC_SIGNALSOURCE_* \ref define_glsync + int iSignalSource; +/// Use sampled sync signal. A value of 0 specifies no sampling. + int iSampleRate; +/// For interlaced sync signals, the value can be ADL_GLSYNC_SYNCFIELD_1 or *_BOTH \ref define_glsync + int iSyncField; +/// The signal edge that should trigger synchronization. ADL_GLSYNC_TRIGGEREDGE_* \ref define_glsync + int iTriggerEdge; +/// Scan rate multiplier applied to the sync signal. ADL_GLSYNC_SCANRATECOEFF_* \ref define_glsync + int iScanRateCoeff; +}ADLGLSyncGenlockConfig, *LPADLGLSyncGenlockConfig; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing GL-Sync port information. +/// +/// This structure is used to get status of the GL-Sync ports (BNC or RJ45s) +/// for Workstation Framelock/Genlock. +/// \see define_glsync +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGlSyncPortInfo +{ +/// Type of GL-Sync port (ADL_GLSYNC_PORT_*). + int iPortType; +/// The number of LEDs for this port. It's also filled within ADLGLSyncPortCaps. + int iNumOfLEDs; +/// Port state ADL_GLSYNC_PORTSTATE_* \ref define_glsync + int iPortState; +/// Scanned frequency for this port (vertical refresh rate in milliHz; 60000 means 60 Hz). + int iFrequency; +/// Used for ADL_GLSYNC_PORT_BNC. It is ADL_GLSYNC_SIGNALTYPE_* \ref define_glsync + int iSignalType; +/// Used for ADL_GLSYNC_PORT_RJ45PORT*. It is GL_Sync GPU Port index or ADL_GLSYNC_SIGNALSOURCE_*. \ref define_glsync + int iSignalSource; + +} ADLGlSyncPortInfo, *LPADLGlSyncPortInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing GL-Sync port control settings. +/// +/// This structure is used to configure the GL-Sync ports (RJ45s only) +/// for Workstation Framelock/Genlock. +/// \see define_glsync +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGlSyncPortControl +{ +/// Port to control ADL_GLSYNC_PORT_RJ45PORT1 or ADL_GLSYNC_PORT_RJ45PORT2 \ref define_glsync + int iPortType; +/// Port control data ADL_GLSYNC_PORTCNTL_* \ref define_glsync + int iControlVector; +/// Source of the sync signal. Either GL_Sync GPU Port index or ADL_GLSYNC_SIGNALSOURCE_* \ref define_glsync + int iSignalSource; +} ADLGlSyncPortControl; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing GL-Sync mode of a display. +/// +/// This structure is used to get and set GL-Sync mode settings for a display connected to +/// an adapter attached to a GL-Sync module for Workstation Framelock/Genlock. +/// \see define_glsync +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGlSyncMode +{ +/// Mode control vector. Bitfield of ADL_GLSYNC_MODECNTL_* \ref define_glsync + int iControlVector; +/// Mode status vector. Bitfield of ADL_GLSYNC_MODECNTL_STATUS_* \ref define_glsync + int iStatusVector; +/// Index of GL-Sync connector used to genlock the display/controller. + int iGLSyncConnectorIndex; +} ADLGlSyncMode, *LPADLGlSyncMode; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing GL-Sync mode of a display. +/// +/// This structure is used to get and set GL-Sync mode settings for a display connected to +/// an adapter attached to a GL-Sync module for Workstation Framelock/Genlock. +/// \see define_glsync +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGlSyncMode2 +{ +/// Mode control vector. Bitfield of ADL_GLSYNC_MODECNTL_* \ref define_glsync + int iControlVector; +/// Mode status vector. Bitfield of ADL_GLSYNC_MODECNTL_STATUS_* \ref define_glsync + int iStatusVector; +/// Index of GL-Sync connector used to genlock the display/controller. + int iGLSyncConnectorIndex; +/// Index of the display to which this GLSync applies to. + int iDisplayIndex; +} ADLGlSyncMode2, *LPADLGlSyncMode2; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the packet info of a display. +/// +/// This structure is used to get and set the packet information of a display. +/// This structure is used by ADLDisplayDataPacket. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLInfoPacket +{ + char hb0; + char hb1; + char hb2; +/// sb0~sb27 + char sb[28]; +}ADLInfoPacket; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the AVI packet info of a display. +/// +/// This structure is used to get and set AVI the packet info of a display. +/// This structure is used by ADLDisplayDataPacket. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLAVIInfoPacket //Valid user defined data/ +{ +/// byte 3, bit 7 + char bPB3_ITC; +/// byte 5, bit [7:4]. + char bPB5; +}ADLAVIInfoPacket; + +// Overdrive clock setting structure definition. + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the Overdrive clock setting. +/// +/// This structure is used to get the Overdrive clock setting. +/// This structure is used by ADLAdapterODClockInfo. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODClockSetting +{ +/// Deafult clock + int iDefaultClock; +/// Current clock + int iCurrentClock; +/// Maximum clcok + int iMaxClock; +/// Minimum clock + int iMinClock; +/// Requested clcock + int iRequestedClock; +/// Step + int iStepClock; +} ADLODClockSetting; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the Overdrive clock information. +/// +/// This structure is used to get the Overdrive clock information. +/// This structure is used by the ADL_Display_ODClockInfo_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLAdapterODClockInfo +{ +/// Size of the structure + int iSize; +/// Flag \ref define_clockinfo_flags + int iFlags; +/// Memory Clock + ADLODClockSetting sMemoryClock; +/// Engine Clock + ADLODClockSetting sEngineClock; +} ADLAdapterODClockInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the Overdrive clock configuration. +/// +/// This structure is used to set the Overdrive clock configuration. +/// This structure is used by the ADL_Display_ODClockConfig_Set() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLAdapterODClockConfig +{ +/// Size of the structure + int iSize; +/// Flag \ref define_clockinfo_flags + int iFlags; +/// Memory Clock + int iMemoryClock; +/// Engine Clock + int iEngineClock; +} ADLAdapterODClockConfig; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about current power management related activity. +/// +/// This structure is used to store information about current power management related activity. +/// This structure (Overdrive 5 interfaces) is used by the ADL_PM_CurrentActivity_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLPMActivity +{ +/// Must be set to the size of the structure + int iSize; +/// Current engine clock. + int iEngineClock; +/// Current memory clock. + int iMemoryClock; +/// Current core voltage. + int iVddc; +/// GPU utilization. + int iActivityPercent; +/// Performance level index. + int iCurrentPerformanceLevel; +/// Current PCIE bus speed. + int iCurrentBusSpeed; +/// Number of PCIE bus lanes. + int iCurrentBusLanes; +/// Maximum number of PCIE bus lanes. + int iMaximumBusLanes; +/// Reserved for future purposes. + int iReserved; +} ADLPMActivity; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about thermal controller. +/// +/// This structure is used to store information about thermal controller. +/// This structure is used by ADL_PM_ThermalDevices_Enum. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLThermalControllerInfo +{ +/// Must be set to the size of the structure + int iSize; +/// Possible valies: \ref ADL_DL_THERMAL_DOMAIN_OTHER or \ref ADL_DL_THERMAL_DOMAIN_GPU. + int iThermalDomain; +/// GPU 0, 1, etc. + int iDomainIndex; +/// Possible valies: \ref ADL_DL_THERMAL_FLAG_INTERRUPT or \ref ADL_DL_THERMAL_FLAG_FANCONTROL + int iFlags; +} ADLThermalControllerInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about thermal controller temperature. +/// +/// This structure is used to store information about thermal controller temperature. +/// This structure is used by the ADL_PM_Temperature_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLTemperature +{ +/// Must be set to the size of the structure + int iSize; +/// Temperature in millidegrees Celsius. + int iTemperature; +} ADLTemperature; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about thermal controller fan speed. +/// +/// This structure is used to store information about thermal controller fan speed. +/// This structure is used by the ADL_PM_FanSpeedInfo_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLFanSpeedInfo +{ +/// Must be set to the size of the structure + int iSize; +/// \ref define_fanctrl + int iFlags; +/// Minimum possible fan speed value in percents. + int iMinPercent; +/// Maximum possible fan speed value in percents. + int iMaxPercent; +/// Minimum possible fan speed value in RPM. + int iMinRPM; +/// Maximum possible fan speed value in RPM. + int iMaxRPM; +} ADLFanSpeedInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about fan speed reported by thermal controller. +/// +/// This structure is used to store information about fan speed reported by thermal controller. +/// This structure is used by the ADL_Overdrive5_FanSpeed_Get() and ADL_Overdrive5_FanSpeed_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLFanSpeedValue +{ +/// Must be set to the size of the structure + int iSize; +/// Possible valies: \ref ADL_DL_FANCTRL_SPEED_TYPE_PERCENT or \ref ADL_DL_FANCTRL_SPEED_TYPE_RPM + int iSpeedType; +/// Fan speed value + int iFanSpeed; +/// The only flag for now is: \ref ADL_DL_FANCTRL_FLAG_USER_DEFINED_SPEED + int iFlags; +} ADLFanSpeedValue; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the range of Overdrive parameter. +/// +/// This structure is used to store information about the range of Overdrive parameter. +/// This structure is used by ADLODParameters. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODParameterRange +{ +/// Minimum parameter value. + int iMin; +/// Maximum parameter value. + int iMax; +/// Parameter step value. + int iStep; +} ADLODParameterRange; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive parameters. +/// +/// This structure is used to store information about Overdrive parameters. +/// This structure is used by the ADL_Overdrive5_ODParameters_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODParameters +{ +/// Must be set to the size of the structure + int iSize; +/// Number of standard performance states. + int iNumberOfPerformanceLevels; +/// Indicates whether the GPU is capable to measure its activity. + int iActivityReportingSupported; +/// Indicates whether the GPU supports discrete performance levels or performance range. + int iDiscretePerformanceLevels; +/// Reserved for future use. + int iReserved; +/// Engine clock range. + ADLODParameterRange sEngineClock; +/// Memory clock range. + ADLODParameterRange sMemoryClock; +/// Core voltage range. + ADLODParameterRange sVddc; +} ADLODParameters; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive level. +/// +/// This structure is used to store information about Overdrive level. +/// This structure is used by ADLODPerformanceLevels. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODPerformanceLevel +{ +/// Engine clock. + int iEngineClock; +/// Memory clock. + int iMemoryClock; +/// Core voltage. + int iVddc; +} ADLODPerformanceLevel; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive performance levels. +/// +/// This structure is used to store information about Overdrive performance levels. +/// This structure is used by the ADL_Overdrive5_ODPerformanceLevels_Get() and ADL_Overdrive5_ODPerformanceLevels_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODPerformanceLevels +{ +/// Must be set to sizeof( \ref ADLODPerformanceLevels ) + sizeof( \ref ADLODPerformanceLevel ) * (ADLODParameters.iNumberOfPerformanceLevels - 1) + int iSize; + int iReserved; +/// Array of performance state descriptors. Must have ADLODParameters.iNumberOfPerformanceLevels elements. + ADLODPerformanceLevel aLevels [1]; +} ADLODPerformanceLevels; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the proper CrossfireX chains combinations. +/// +/// This structure is used to store information about the CrossfireX chains combination for a particular adapter. +/// This structure is used by the ADL_Adapter_Crossfire_Caps(), ADL_Adapter_Crossfire_Get(), and ADL_Adapter_Crossfire_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLCrossfireComb +{ +/// Number of adapters in this combination. + int iNumLinkAdapter; +/// A list of ADL indexes of the linked adapters in this combination. + int iAdaptLink[3]; +} ADLCrossfireComb; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing CrossfireX state and error information. +/// +/// This structure is used to store state and error information about a particular adapter CrossfireX combination. +/// This structure is used by the ADL_Adapter_Crossfire_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLCrossfireInfo +{ +/// Current error code of this CrossfireX combination. + int iErrorCode; +/// Current \ref define_crossfirestate + int iState; +/// If CrossfireX is supported by this combination. The value is either \ref ADL_TRUE or \ref ADL_FALSE. + int iSupported; +} ADLCrossfireInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about the BIOS. +/// +/// This structure is used to store various information about the Chipset. This +/// information can be returned to the user. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLBiosInfo +{ + char strPartNumber[ADL_MAX_PATH]; ///< Part number. + char strVersion[ADL_MAX_PATH]; ///< Version number. + char strDate[ADL_MAX_PATH]; ///< BIOS date in yyyy/mm/dd hh:mm format. +} ADLBiosInfo, *LPADLBiosInfo; + + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about adapter location. +/// +/// This structure is used to store information about adapter location. +/// This structure is used by ADLMVPUStatus. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLAdapterLocation +{ +/// PCI Bus number : 8 bits + int iBus; +/// Device number : 5 bits + int iDevice; +/// Function number : 3 bits + int iFunction; +} ADLAdapterLocation,ADLBdf; + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing version information +/// +/// This structure is used to store software version information, description of the display device and a web link to the latest installed Catalyst drivers. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLVersionsInfo +{ + /// Driver Release (Packaging) Version (e.g. 8.71-100128n-094835E-ATI) + char strDriverVer[ADL_MAX_PATH]; + /// Catalyst Version(e.g. "10.1"). + char strCatalystVersion[ADL_MAX_PATH]; + /// Web link to an XML file with information about the latest AMD drivers and locations (e.g. "http://www.amd.com/us/driverxml" ) + char strCatalystWebLink[ADL_MAX_PATH]; + +} ADLVersionsInfo, *LPADLVersionsInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing version information +/// +/// This structure is used to store software version information, description of the display device and a web link to the latest installed Catalyst drivers. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLVersionsInfoX2 +{ + /// Driver Release (Packaging) Version (e.g. "16.20.1035-160621a-303814C") + char strDriverVer[ADL_MAX_PATH]; + /// Catalyst Version(e.g. "15.8"). + char strCatalystVersion[ADL_MAX_PATH]; + /// Crimson Version(e.g. "16.6.2"). + char strCrimsonVersion[ADL_MAX_PATH]; + /// Web link to an XML file with information about the latest AMD drivers and locations (e.g. "http://support.amd.com/drivers/xml/driver_09_us.xml" ) + char strCatalystWebLink[ADL_MAX_PATH]; + +} ADLVersionsInfoX2, *LPADLVersionsInfoX2; + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about MultiVPU capabilities. +/// +/// This structure is used to store information about MultiVPU capabilities. +/// This structure is used by the ADL_Display_MVPUCaps_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLMVPUCaps +{ +/// Must be set to sizeof( ADLMVPUCaps ). + int iSize; +/// Number of adapters. + int iAdapterCount; +/// Bits set for all possible MVPU masters. \ref MVPU_ADAPTER_0 .. \ref MVPU_ADAPTER_3 + int iPossibleMVPUMasters; +/// Bits set for all possible MVPU slaves. \ref MVPU_ADAPTER_0 .. \ref MVPU_ADAPTER_3 + int iPossibleMVPUSlaves; +/// Registry path for each adapter. + char cAdapterPath[ADL_DL_MAX_MVPU_ADAPTERS][ADL_DL_MAX_REGISTRY_PATH]; +} ADLMVPUCaps; + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about MultiVPU status. +/// +/// This structure is used to store information about MultiVPU status. +/// Ths structure is used by the ADL_Display_MVPUStatus_Get() function. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLMVPUStatus +{ +/// Must be set to sizeof( ADLMVPUStatus ). + int iSize; +/// Number of active adapters. + int iActiveAdapterCount; +/// MVPU status. + int iStatus; +/// PCI Bus/Device/Function for each active adapter participating in MVPU. + ADLAdapterLocation aAdapterLocation[ADL_DL_MAX_MVPU_ADAPTERS]; +} ADLMVPUStatus; + +// Displays Manager structures + +/////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about the activatable source. +/// +/// This structure is used to store activatable source information +/// This information can be returned to the user. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLActivatableSource +{ + /// The Persistent logical Adapter Index. + int iAdapterIndex; + /// The number of Activatable Sources. + int iNumActivatableSources; + /// The bit mask identifies the number of bits ActivatableSourceValue is using. (Not currnetly used) + int iActivatableSourceMask; + /// The bit mask identifies the status. (Not currnetly used) + int iActivatableSourceValue; +} ADLActivatableSource, *LPADLActivatableSource; + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about display mode. +/// +/// This structure is used to store the display mode for the current adapter +/// such as X, Y positions, screen resolutions, orientation, +/// color depth, refresh rate, progressive or interlace mode, etc. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + +typedef struct ADLMode +{ +/// Adapter index. + int iAdapterIndex; +/// Display IDs. + ADLDisplayID displayID; +/// Screen position X coordinate. + int iXPos; +/// Screen position Y coordinate. + int iYPos; +/// Screen resolution Width. + int iXRes; +/// Screen resolution Height. + int iYRes; +/// Screen Color Depth. E.g., 16, 32. + int iColourDepth; +/// Screen refresh rate. Could be fractional E.g. 59.97 + float fRefreshRate; +/// Screen orientation. E.g., 0, 90, 180, 270. + int iOrientation; +/// Vista mode flag indicating Progressive or Interlaced mode. + int iModeFlag; +/// The bit mask identifying the number of bits this Mode is currently using. It is the sum of all the bit definitions defined in \ref define_displaymode + int iModeMask; +/// The bit mask identifying the display status. The detailed definition is in \ref define_displaymode + int iModeValue; +} ADLMode, *LPADLMode; + + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about display target information. +/// +/// This structure is used to store the display target information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayTarget +{ + /// The Display ID. + ADLDisplayID displayID; + + /// The display map index identify this manner and the desktop surface. + int iDisplayMapIndex; + + /// The bit mask identifies the number of bits DisplayTarget is currently using. It is the sum of all the bit definitions defined in \ref ADL_DISPLAY_DISPLAYTARGET_PREFERRED. + int iDisplayTargetMask; + + /// The bit mask identifies the display status. The detailed definition is in \ref ADL_DISPLAY_DISPLAYTARGET_PREFERRED. + int iDisplayTargetValue; + +} ADLDisplayTarget, *LPADLDisplayTarget; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display SLS bezel Mode information. +/// +/// This structure is used to store the display SLS bezel Mode information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct tagADLBezelTransientMode +{ + /// Adapter Index + int iAdapterIndex; + + /// SLS Map Index + int iSLSMapIndex; + + /// The mode index + int iSLSModeIndex; + + /// The mode + ADLMode displayMode; + + /// The number of bezel offsets belongs to this map + int iNumBezelOffset; + + /// The first bezel offset array index in the native mode array + int iFirstBezelOffsetArrayIndex; + + /// The bit mask identifies the bits this structure is currently using. It will be the total OR of all the bit definitions. + int iSLSBezelTransientModeMask; + + /// The bit mask identifies the display status. The detail definition is defined below. + int iSLSBezelTransientModeValue; + +} ADLBezelTransientMode, *LPADLBezelTransientMode; + + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about the adapter display manner. +/// +/// This structure is used to store adapter display manner information +/// This information can be returned to the user. Alternatively, it can be used to access various driver calls to +/// fetch various display device related display manner settings upon the user's request. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLAdapterDisplayCap +{ + /// The Persistent logical Adapter Index. + int iAdapterIndex; + /// The bit mask identifies the number of bits AdapterDisplayCap is currently using. Sum all the bits defined in ADL_ADAPTER_DISPLAYCAP_XXX + int iAdapterDisplayCapMask; + /// The bit mask identifies the status. Refer to ADL_ADAPTER_DISPLAYCAP_XXX + int iAdapterDisplayCapValue; +} ADLAdapterDisplayCap, *LPADLAdapterDisplayCap; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about display mapping. +/// +/// This structure is used to store the display mapping data such as display manner. +/// For displays with horizontal or vertical stretch manner, +/// this structure also stores the display order, display row, and column data. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayMap +{ +/// The current display map index. It is the OS desktop index. For example, if the OS index 1 is showing clone mode, the display map will be 1. + int iDisplayMapIndex; + +/// The Display Mode for the current map + ADLMode displayMode; + +/// The number of display targets belongs to this map\n + int iNumDisplayTarget; + +/// The first target array index in the Target array\n + int iFirstDisplayTargetArrayIndex; + +/// The bit mask identifies the number of bits DisplayMap is currently using. It is the sum of all the bit definitions defined in ADL_DISPLAY_DISPLAYMAP_MANNER_xxx. + int iDisplayMapMask; + +///The bit mask identifies the display status. The detailed definition is in ADL_DISPLAY_DISPLAYMAP_MANNER_xxx. + int iDisplayMapValue; + +} ADLDisplayMap, *LPADLDisplayMap; + + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about the display device possible map for one GPU +/// +/// This structure is used to store the display device possible map +/// This information can be returned to the user. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLPossibleMap +{ + /// The current PossibleMap index. Each PossibleMap is assigned an index + int iIndex; + /// The adapter index identifying the GPU for which to validate these Maps & Targets + int iAdapterIndex; + /// Number of display Maps for this GPU to be validated + int iNumDisplayMap; + /// The display Maps list to validate + ADLDisplayMap* displayMap; + /// the number of display Targets for these display Maps + int iNumDisplayTarget; + /// The display Targets list for these display Maps to be validated. + ADLDisplayTarget* displayTarget; +} ADLPossibleMap, *LPADLPossibleMap; + + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about display possible mapping. +/// +/// This structure is used to store the display possible mapping's controller index for the current display. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLPossibleMapping +{ + int iDisplayIndex; ///< The display index. Each display is assigned an index. + int iDisplayControllerIndex; ///< The controller index to which display is mapped. + int iDisplayMannerSupported; ///< The supported display manner. +} ADLPossibleMapping, *LPADLPossibleMapping; + +///////////////////////////////////////////////////////////////////////////////////////////// +/// \brief Structure containing information about the validated display device possible map result. +/// +/// This structure is used to store the validated display device possible map result +/// This information can be returned to the user. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLPossibleMapResult +{ + /// The current display map index. It is the OS Desktop index. For example, OS Index 1 showing clone mode. The Display Map will be 1. + int iIndex; + // The bit mask identifies the number of bits PossibleMapResult is currently using. It will be the sum all the bit definitions defined in ADL_DISPLAY_POSSIBLEMAPRESULT_VALID. + int iPossibleMapResultMask; + /// The bit mask identifies the possible map result. The detail definition is defined in ADL_DISPLAY_POSSIBLEMAPRESULT_XXX. + int iPossibleMapResultValue; +} ADLPossibleMapResult, *LPADLPossibleMapResult; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display SLS Grid information. +/// +/// This structure is used to store the display SLS Grid information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLSLSGrid +{ +/// The Adapter index. + int iAdapterIndex; + +/// The grid index. + int iSLSGridIndex; + +/// The grid row. + int iSLSGridRow; + +/// The grid column. + int iSLSGridColumn; + +/// The grid bit mask identifies the number of bits DisplayMap is currently using. Sum of all bits defined in ADL_DISPLAY_SLSGRID_ORIENTATION_XXX + int iSLSGridMask; + +/// The grid bit value identifies the display status. Refer to ADL_DISPLAY_SLSGRID_ORIENTATION_XXX + int iSLSGridValue; + +} ADLSLSGrid, *LPADLSLSGrid; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display SLS Map information. +/// +/// This structure is used to store the display SLS Map information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLSLSMap +{ + /// The Adapter Index + int iAdapterIndex; + + /// The current display map index. It is the OS Desktop index. For example, OS Index 1 showing clone mode. The Display Map will be 1. + int iSLSMapIndex; + + /// Indicate the current grid + ADLSLSGrid grid; + + /// OS surface index + int iSurfaceMapIndex; + + /// Screen orientation. E.g., 0, 90, 180, 270 + int iOrientation; + + /// The number of display targets belongs to this map + int iNumSLSTarget; + + /// The first target array index in the Target array + int iFirstSLSTargetArrayIndex; + + /// The number of native modes belongs to this map + int iNumNativeMode; + + /// The first native mode array index in the native mode array + int iFirstNativeModeArrayIndex; + + /// The number of bezel modes belongs to this map + int iNumBezelMode; + + /// The first bezel mode array index in the native mode array + int iFirstBezelModeArrayIndex; + + /// The number of bezel offsets belongs to this map + int iNumBezelOffset; + + /// The first bezel offset array index in the + int iFirstBezelOffsetArrayIndex; + + /// The bit mask identifies the number of bits DisplayMap is currently using. Sum all the bit definitions defined in ADL_DISPLAY_SLSMAP_XXX. + int iSLSMapMask; + + /// The bit mask identifies the display map status. Refer to ADL_DISPLAY_SLSMAP_XXX + int iSLSMapValue; + + +} ADLSLSMap, *LPADLSLSMap; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display SLS Offset information. +/// +/// This structure is used to store the display SLS Offset information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLSLSOffset +{ + /// The Adapter Index + int iAdapterIndex; + + /// The current display map index. It is the OS Desktop index. For example, OS Index 1 showing clone mode. The Display Map will be 1. + int iSLSMapIndex; + + /// The Display ID. + ADLDisplayID displayID; + + /// SLS Bezel Mode Index + int iBezelModeIndex; + + /// SLS Bezel Offset X + int iBezelOffsetX; + + /// SLS Bezel Offset Y + int iBezelOffsetY; + + /// SLS Display Width + int iDisplayWidth; + + /// SLS Display Height + int iDisplayHeight; + + /// The bit mask identifies the number of bits Offset is currently using. + int iBezelOffsetMask; + + /// The bit mask identifies the display status. + int iBezelffsetValue; +} ADLSLSOffset, *LPADLSLSOffset; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display SLS Mode information. +/// +/// This structure is used to store the display SLS Mode information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLSLSMode +{ + /// The Adapter Index + int iAdapterIndex; + + /// The current display map index. It is the OS Desktop index. For example, OS Index 1 showing clone mode. The Display Map will be 1. + int iSLSMapIndex; + + /// The mode index + int iSLSModeIndex; + + /// The mode for this map. + ADLMode displayMode; + + /// The bit mask identifies the number of bits Mode is currently using. + int iSLSNativeModeMask; + + /// The bit mask identifies the display status. + int iSLSNativeModeValue; +} ADLSLSMode, *LPADLSLSMode; + + + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the display Possible SLS Map information. +/// +/// This structure is used to store the display Possible SLS Map information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLPossibleSLSMap +{ + /// The current display map index. It is the OS Desktop index. + /// For example, OS Index 1 showing clone mode. The Display Map will be 1. + int iSLSMapIndex; + + /// Number of display map to be validated. + int iNumSLSMap; + + /// The display map list for validation + ADLSLSMap* lpSLSMap; + + /// the number of display map config to be validated. + int iNumSLSTarget; + + /// The display target list for validation. + ADLDisplayTarget* lpDisplayTarget; +} ADLPossibleSLSMap, *LPADLPossibleSLSMap; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the SLS targets. +/// +/// This structure is used to store the SLS targets information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLSLSTarget +{ + /// the logic adapter index + int iAdapterIndex; + + /// The SLS map index + int iSLSMapIndex; + + /// The target ID + ADLDisplayTarget displayTarget; + + /// Target postion X in SLS grid + int iSLSGridPositionX; + + /// Target postion Y in SLS grid + int iSLSGridPositionY; + + /// The view size width, height and rotation angle per SLS Target + ADLMode viewSize; + + /// The bit mask identifies the bits in iSLSTargetValue are currently used + int iSLSTargetMask; + + /// The bit mask identifies status info. It is for function extension purpose + int iSLSTargetValue; + +} ADLSLSTarget, *LPADLSLSTarget; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the Adapter offset stepping size. +/// +/// This structure is used to store the Adapter offset stepping size information. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLBezelOffsetSteppingSize +{ + /// the logic adapter index + int iAdapterIndex; + + /// The SLS map index + int iSLSMapIndex; + + /// Bezel X stepping size offset + int iBezelOffsetSteppingSizeX; + + /// Bezel Y stepping size offset + int iBezelOffsetSteppingSizeY; + + /// Identifies the bits this structure is currently using. It will be the total OR of all the bit definitions. + int iBezelOffsetSteppingSizeMask; + + /// Bit mask identifies the display status. + int iBezelOffsetSteppingSizeValue; + +} ADLBezelOffsetSteppingSize, *LPADLBezelOffsetSteppingSize; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about the overlap offset info for all the displays for each SLS mode. +/// +/// This structure is used to store the no. of overlapped modes for each SLS Mode once user finishes the configuration from Overlap Widget +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLSLSOverlappedMode +{ + /// the SLS mode for which the overlap is configured + ADLMode SLSMode; + /// the number of target displays in SLS. + int iNumSLSTarget; + /// the first target array index in the target array + int iFirstTargetArrayIndex; +}ADLSLSTargetOverlap, *LPADLSLSTargetOverlap; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about driver supported PowerExpress Config Caps +/// +/// This structure is used to store the driver supported PowerExpress Config Caps +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLPXConfigCaps +{ + /// The Persistent logical Adapter Index. + int iAdapterIndex; + + /// The bit mask identifies the number of bits PowerExpress Config Caps is currently using. It is the sum of all the bit definitions defined in ADL_PX_CONFIGCAPS_XXXX /ref define_powerxpress_constants. + int iPXConfigCapMask; + + /// The bit mask identifies the PowerExpress Config Caps value. The detailed definition is in ADL_PX_CONFIGCAPS_XXXX /ref define_powerxpress_constants. + int iPXConfigCapValue; + +} ADLPXConfigCaps, *LPADLPXConfigCaps; + +///////////////////////////////////////////////////////////////////////////////////////// +///\brief Enum containing PX or HG type +/// +/// This enum is used to get PX or hG type +/// +/// \nosubgrouping +////////////////////////////////////////////////////////////////////////////////////////// +enum ADLPxType +{ + //Not AMD related PX/HG or not PX or HG at all + ADL_PX_NONE = 0, + //A+A PX + ADL_SWITCHABLE_AMDAMD = 1, + // A+A HG + ADL_HG_AMDAMD = 2, + //A+I PX + ADL_SWITCHABLE_AMDOTHER = 3, + //A+I HG + ADL_HG_AMDOTHER = 4, +}; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about an application +/// +/// This structure is used to store basic information of an application +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLApplicationData +{ + /// Path Name + char strPathName[ADL_MAX_PATH]; + /// File Name + char strFileName[ADL_APP_PROFILE_FILENAME_LENGTH]; + /// Creation timestamp + char strTimeStamp[ADL_APP_PROFILE_TIMESTAMP_LENGTH]; + /// Version + char strVersion[ADL_APP_PROFILE_VERSION_LENGTH]; +}ADLApplicationData; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about an application +/// +/// This structure is used to store basic information of an application +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLApplicationDataX2 +{ + /// Path Name + wchar_t strPathName[ADL_MAX_PATH]; + /// File Name + wchar_t strFileName[ADL_APP_PROFILE_FILENAME_LENGTH]; + /// Creation timestamp + wchar_t strTimeStamp[ADL_APP_PROFILE_TIMESTAMP_LENGTH]; + /// Version + wchar_t strVersion[ADL_APP_PROFILE_VERSION_LENGTH]; +}ADLApplicationDataX2; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about an application +/// +/// This structure is used to store basic information of an application including process id +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLApplicationDataX3 +{ + /// Path Name + wchar_t strPathName[ADL_MAX_PATH]; + /// File Name + wchar_t strFileName[ADL_APP_PROFILE_FILENAME_LENGTH]; + /// Creation timestamp + wchar_t strTimeStamp[ADL_APP_PROFILE_TIMESTAMP_LENGTH]; + /// Version + wchar_t strVersion[ADL_APP_PROFILE_VERSION_LENGTH]; + //Application Process id + unsigned int iProcessId; +}ADLApplicationDataX3; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information of a property of an application profile +/// +/// This structure is used to store property information of an application profile +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _PropertyRecord +{ + /// Property Name + char strName [ADL_APP_PROFILE_PROPERTY_LENGTH]; + /// Property Type + ADLProfilePropertyType eType; + /// Data Size in bytes + int iDataSize; + /// Property Value, can be any data type + unsigned char uData[1]; +}PropertyRecord; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about an application profile +/// +/// This structure is used to store information of an application profile +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLApplicationProfile +{ + /// Number of properties + int iCount; + /// Buffer to store all property records + PropertyRecord record[1]; +}ADLApplicationProfile; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about an OD5 Power Control feature +/// +/// This structure is used to store information of an Power Control feature +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLPowerControlInfo +{ +/// Minimum value. +int iMinValue; +/// Maximum value. +int iMaxValue; +/// The minimum change in between minValue and maxValue. +int iStepValue; + } ADLPowerControlInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about an controller mode +/// +/// This structure is used to store information of an controller mode +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLControllerMode +{ + /// This falg indicates actions that will be applied by set viewport + /// The value can be a combination of ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_POSITION, + /// ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_PANLOCK and ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_SIZE + int iModifiers; + + /// Horizontal view starting position + int iViewPositionCx; + + /// Vertical view starting position + int iViewPositionCy; + + /// Horizontal left panlock position + int iViewPanLockLeft; + + /// Horizontal right panlock position + int iViewPanLockRight; + + /// Vertical top panlock position + int iViewPanLockTop; + + /// Vertical bottom panlock position + int iViewPanLockBottom; + + /// View resolution in pixels (width) + int iViewResolutionCx; + + /// View resolution in pixels (hight) + int iViewResolutionCy; +}ADLControllerMode; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about a display +/// +/// This structure is used to store information about a display +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayIdentifier +{ + /// ADL display index + long ulDisplayIndex; + + /// manufacturer ID of the display + long ulManufacturerId; + + /// product ID of the display + long ulProductId; + + /// serial number of the display + long ulSerialNo; + +} ADLDisplayIdentifier; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 clock range +/// +/// This structure is used to store information about Overdrive 6 clock range +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6ParameterRange +{ + /// The starting value of the clock range + int iMin; + /// The ending value of the clock range + int iMax; + /// The minimum increment between clock values + int iStep; + +} ADLOD6ParameterRange; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 capabilities +/// +/// This structure is used to store information about Overdrive 6 capabilities +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6Capabilities +{ + /// Contains a bitmap of the OD6 capability flags. Possible values: \ref ADL_OD6_CAPABILITY_SCLK_CUSTOMIZATION, + /// \ref ADL_OD6_CAPABILITY_MCLK_CUSTOMIZATION, \ref ADL_OD6_CAPABILITY_GPU_ACTIVITY_MONITOR + int iCapabilities; + /// Contains a bitmap indicating the power states + /// supported by OD6. Currently only the performance state + /// is supported. Possible Values: \ref ADL_OD6_SUPPORTEDSTATE_PERFORMANCE + int iSupportedStates; + /// Number of levels. OD6 will always use 2 levels, which describe + /// the minimum to maximum clock ranges. + /// The 1st level indicates the minimum clocks, and the 2nd level + /// indicates the maximum clocks. + int iNumberOfPerformanceLevels; + /// Contains the hard limits of the sclk range. Overdrive + /// clocks cannot be set outside this range. + ADLOD6ParameterRange sEngineClockRange; + /// Contains the hard limits of the mclk range. Overdrive + /// clocks cannot be set outside this range. + ADLOD6ParameterRange sMemoryClockRange; + + /// Value for future extension + int iExtValue; + /// Mask for future extension + int iExtMask; + +} ADLOD6Capabilities; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 clock values. +/// +/// This structure is used to store information about Overdrive 6 clock values. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6PerformanceLevel +{ + /// Engine (core) clock. + int iEngineClock; + /// Memory clock. + int iMemoryClock; + +} ADLOD6PerformanceLevel; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 clocks. +/// +/// This structure is used to store information about Overdrive 6 clocks. This is a +/// variable-sized structure. iNumberOfPerformanceLevels indicate how many elements +/// are contained in the aLevels array. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6StateInfo +{ + /// Number of levels. OD6 uses clock ranges instead of discrete performance levels. + /// iNumberOfPerformanceLevels is always 2. The 1st level indicates the minimum clocks + /// in the range. The 2nd level indicates the maximum clocks in the range. + int iNumberOfPerformanceLevels; + + /// Value for future extension + int iExtValue; + /// Mask for future extension + int iExtMask; + + /// Variable-sized array of levels. + /// The number of elements in the array is specified by iNumberofPerformanceLevels. + ADLOD6PerformanceLevel aLevels [1]; + +} ADLOD6StateInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about current Overdrive 6 performance status. +/// +/// This structure is used to store information about current Overdrive 6 performance status. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6CurrentStatus +{ + /// Current engine clock in 10 KHz. + int iEngineClock; + /// Current memory clock in 10 KHz. + int iMemoryClock; + /// Current GPU activity in percent. This + /// indicates how "busy" the GPU is. + int iActivityPercent; + /// Not used. Reserved for future use. + int iCurrentPerformanceLevel; + /// Current PCI-E bus speed + int iCurrentBusSpeed; + /// Current PCI-E bus # of lanes + int iCurrentBusLanes; + /// Maximum possible PCI-E bus # of lanes + int iMaximumBusLanes; + + /// Value for future extension + int iExtValue; + /// Mask for future extension + int iExtMask; + +} ADLOD6CurrentStatus; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 thermal contoller capabilities +/// +/// This structure is used to store information about Overdrive 6 thermal controller capabilities +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6ThermalControllerCaps +{ + /// Contains a bitmap of thermal controller capability flags. Possible values: \ref ADL_OD6_TCCAPS_THERMAL_CONTROLLER, \ref ADL_OD6_TCCAPS_FANSPEED_CONTROL, + /// \ref ADL_OD6_TCCAPS_FANSPEED_PERCENT_READ, \ref ADL_OD6_TCCAPS_FANSPEED_PERCENT_WRITE, \ref ADL_OD6_TCCAPS_FANSPEED_RPM_READ, \ref ADL_OD6_TCCAPS_FANSPEED_RPM_WRITE + int iCapabilities; + /// Minimum fan speed expressed as a percentage + int iFanMinPercent; + /// Maximum fan speed expressed as a percentage + int iFanMaxPercent; + /// Minimum fan speed expressed in revolutions-per-minute + int iFanMinRPM; + /// Maximum fan speed expressed in revolutions-per-minute + int iFanMaxRPM; + + /// Value for future extension + int iExtValue; + /// Mask for future extension + int iExtMask; + +} ADLOD6ThermalControllerCaps; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 fan speed information +/// +/// This structure is used to store information about Overdrive 6 fan speed information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6FanSpeedInfo +{ + /// Contains a bitmap of the valid fan speed type flags. Possible values: \ref ADL_OD6_FANSPEED_TYPE_PERCENT, \ref ADL_OD6_FANSPEED_TYPE_RPM, \ref ADL_OD6_FANSPEED_USER_DEFINED + int iSpeedType; + /// Contains current fan speed in percent (if valid flag exists in iSpeedType) + int iFanSpeedPercent; + /// Contains current fan speed in RPM (if valid flag exists in iSpeedType) + int iFanSpeedRPM; + + /// Value for future extension + int iExtValue; + /// Mask for future extension + int iExtMask; + +} ADLOD6FanSpeedInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 fan speed value +/// +/// This structure is used to store information about Overdrive 6 fan speed value +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6FanSpeedValue +{ + /// Indicates the units of the fan speed. Possible values: \ref ADL_OD6_FANSPEED_TYPE_PERCENT, \ref ADL_OD6_FANSPEED_TYPE_RPM + int iSpeedType; + /// Fan speed value (units as indicated above) + int iFanSpeed; + + /// Value for future extension + int iExtValue; + /// Mask for future extension + int iExtMask; + +} ADLOD6FanSpeedValue; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 PowerControl settings. +/// +/// This structure is used to store information about Overdrive 6 PowerControl settings. +/// PowerControl is the feature which allows the performance characteristics of the GPU +/// to be adjusted by changing the PowerTune power limits. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6PowerControlInfo +{ + /// The minimum PowerControl adjustment value + int iMinValue; + /// The maximum PowerControl adjustment value + int iMaxValue; + /// The minimum difference between PowerControl adjustment values + int iStepValue; + + /// Value for future extension + int iExtValue; + /// Mask for future extension + int iExtMask; + +} ADLOD6PowerControlInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 PowerControl settings. +/// +/// This structure is used to store information about Overdrive 6 PowerControl settings. +/// PowerControl is the feature which allows the performance characteristics of the GPU +/// to be adjusted by changing the PowerTune power limits. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6VoltageControlInfo +{ + /// The minimum VoltageControl adjustment value + int iMinValue; + /// The maximum VoltageControl adjustment value + int iMaxValue; + /// The minimum difference between VoltageControl adjustment values + int iStepValue; + + /// Value for future extension + int iExtValue; + /// Mask for future extension + int iExtMask; + +} ADLOD6VoltageControlInfo; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing ECC statistics namely SEC counts and DED counts +/// Single error count - count of errors that can be corrected +/// Doubt Error Detect - count of errors that cannot be corrected +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLECCData +{ + // Single error count - count of errors that can be corrected + int iSec; + // Double error detect - count of errors that cannot be corrected + int iDed; + +} ADLECCData; + + + + +/// \brief Handle to ADL client context. +/// +/// ADL clients obtain context handle from initial call to \ref ADL2_Main_Control_Create. +/// Clients have to pass the handle to each subsequent ADL call and finally destroy +/// the context with call to \ref ADL2_Main_Control_Destroy +/// \nosubgrouping +typedef void *ADL_CONTEXT_HANDLE; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the display mode definition used per controller. +/// +/// This structure is used to store the display mode definition used per controller. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDisplayModeX2 +{ +/// Horizontal resolution (in pixels). + int iWidth; +/// Vertical resolution (in lines). + int iHeight; +/// Interlaced/Progressive. The value will be set for Interlaced as ADL_DL_TIMINGFLAG_INTERLACED. If not set it is progressive. Refer define_detailed_timing_flags. + int iScanType; +/// Refresh rate. + int iRefreshRate; +/// Timing Standard. Refer define_modetiming_standard. + int iTimingStandard; +} ADLDisplayModeX2; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 extension capabilities +/// +/// This structure is used to store information about Overdrive 6 extension capabilities +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6CapabilitiesEx +{ + /// Contains a bitmap of the OD6 extension capability flags. Possible values: \ref ADL_OD6_CAPABILITY_SCLK_CUSTOMIZATION, + /// \ref ADL_OD6_CAPABILITY_MCLK_CUSTOMIZATION, \ref ADL_OD6_CAPABILITY_GPU_ACTIVITY_MONITOR, + /// \ref ADL_OD6_CAPABILITY_POWER_CONTROL, \ref ADL_OD6_CAPABILITY_VOLTAGE_CONTROL, \ref ADL_OD6_CAPABILITY_PERCENT_ADJUSTMENT, + //// \ref ADL_OD6_CAPABILITY_THERMAL_LIMIT_UNLOCK + int iCapabilities; + /// The Power states that support clock and power customization. Only performance state is currently supported. + /// Possible Values: \ref ADL_OD6_SUPPORTEDSTATE_PERFORMANCE + int iSupportedStates; + /// Returns the hard limits of the SCLK overdrive adjustment range. Overdrive clocks should not be adjusted outside of this range. The values are specified as +/- percentages. + ADLOD6ParameterRange sEngineClockPercent; + /// Returns the hard limits of the MCLK overdrive adjustment range. Overdrive clocks should not be adjusted outside of this range. The values are specified as +/- percentages. + ADLOD6ParameterRange sMemoryClockPercent; + /// Returns the hard limits of the Power Limit adjustment range. Power limit should not be adjusted outside this range. The values are specified as +/- percentages. + ADLOD6ParameterRange sPowerControlPercent; + /// Reserved for future expansion of the structure. + int iExtValue; + /// Reserved for future expansion of the structure. + int iExtMask; +} ADLOD6CapabilitiesEx; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 extension state information +/// +/// This structure is used to store information about Overdrive 6 extension state information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6StateEx +{ + /// The current engine clock adjustment value, specified as a +/- percent. + int iEngineClockPercent; + /// The current memory clock adjustment value, specified as a +/- percent. + int iMemoryClockPercent; + /// The current power control adjustment value, specified as a +/- percent. + int iPowerControlPercent; + /// Reserved for future expansion of the structure. + int iExtValue; + /// Reserved for future expansion of the structure. + int iExtMask; +} ADLOD6StateEx; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive 6 extension recommended maximum clock adjustment values +/// +/// This structure is used to store information about Overdrive 6 extension recommended maximum clock adjustment values +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD6MaxClockAdjust +{ + /// The recommended maximum engine clock adjustment in percent, for the specified power limit value. + int iEngineClockMax; + /// The recommended maximum memory clock adjustment in percent, for the specified power limit value. + /// Currently the memory is independent of the Power Limit setting, so iMemoryClockMax will always return the maximum + /// possible adjustment value. This field is here for future enhancement in case we add a dependency between Memory Clock + /// adjustment and Power Limit setting. + int iMemoryClockMax; + /// Reserved for future expansion of the structure. + int iExtValue; + /// Reserved for future expansion of the structure. + int iExtMask; +} ADLOD6MaxClockAdjust; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the Connector information +/// +/// this structure is used to get the connector information like length, positions & etc. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLConnectorInfo +{ + ///index of the connector(0-based) + int iConnectorIndex; + ///used for disply identification/ordering + int iConnectorId; + ///index of the slot, 0-based index. + int iSlotIndex; + ///Type of the connector. \ref define_connector_types + int iType; + ///Position of the connector(in millimeters), from the right side of the slot. + int iOffset; + ///Length of the connector(in millimeters). + int iLength; + +} ADLConnectorInfo; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing the slot information +/// +/// this structure is used to get the slot information like length of the slot, no of connectors on the slot & etc. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLBracketSlotInfo +{ + ///index of the slot, 0-based index. + int iSlotIndex; + ///length of the slot(in millimeters). + int iLength; + ///width of the slot(in millimeters). + int iWidth; +} ADLBracketSlotInfo; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing MST branch information +/// +/// this structure is used to store the MST branch information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLMSTRad +{ + ///depth of the link. + int iLinkNumber; + /// Relative address, address scheme starts from source side + char rad[ADL_MAX_RAD_LINK_COUNT]; +} ADLMSTRad; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing port information +/// +/// this structure is used to get the display or MST branch information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLDevicePort +{ + ///index of the connector. + int iConnectorIndex; + ///Relative MST address. If MST RAD contains 0 it means DP or Root of the MST topology. For non DP connectors MST RAD is ignored. + ADLMSTRad aMSTRad; +} ADLDevicePort; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing supported connection types and properties +/// +/// this structure is used to get the supported connection types and supported properties of given connector +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLSupportedConnections +{ + ///Bit vector of supported connections. Bitmask is defined in constants section. \ref define_connection_types + int iSupportedConnections; + ///Array of bitvectors. Each bit vector represents supported properties for one connection type. Index of this array is connection type (bit number in mask). + int iSupportedProperties[ADL_MAX_CONNECTION_TYPES]; +} ADLSupportedConnections; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing connection state of the connector +/// +/// this structure is used to get the current Emulation status and mode of the given connector +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLConnectionState +{ + ///The value is bit vector. Each bit represents status. See masks constants for details. \ref define_emulation_status + int iEmulationStatus; + ///It contains information about current emulation mode. See constants for details. \ref define_emulation_mode + int iEmulationMode; + ///If connection is active it will contain display id, otherwise CWDDEDI_INVALID_DISPLAY_INDEX + int iDisplayIndex; +} ADLConnectionState; + + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing connection properties information +/// +/// this structure is used to retrieve the properties of connection type +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLConnectionProperties +{ + //Bit vector. Represents actual properties. Supported properties for specific connection type. \ref define_connection_properties + int iValidProperties; + //Bitrate(in MHz). Could be used for MST branch, DP or DP active dongle. \ref define_linkrate_constants + int iBitrate; + //Number of lanes in DP connection. \ref define_lanecount_constants + int iNumberOfLanes; + //Color depth(in bits). \ref define_colordepth_constants + int iColorDepth; + //3D capabilities. It could be used for some dongles. For instance: alternate framepack. Value of this property is bit vector. + int iStereo3DCaps; + ///Output Bandwidth. Could be used for MST branch, DP or DP Active dongle. \ref define_linkrate_constants + int iOutputBandwidth; +} ADLConnectionProperties; + +//////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing connection information +/// +/// this structure is used to retrieve the data from driver which includes +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLConnectionData +{ + ///Connection type. based on the connection type either iNumberofPorts or IDataSize,EDIDdata is valid, \ref define_connection_types + int iConnectionType; + ///Specifies the connection properties. + ADLConnectionProperties aConnectionProperties; + ///Number of ports + int iNumberofPorts; + ///Number of Active Connections + int iActiveConnections; + ///actual size of EDID data block size. + int iDataSize; + ///EDID Data + char EdidData[ADL_MAX_DISPLAY_EDID_DATA_SIZE]; +} ADLConnectionData; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about an controller mode including Number of Connectors +/// +/// This structure is used to store information of an controller mode +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLAdapterCapsX2 +{ + /// AdapterID for this adapter + int iAdapterID; + /// Number of controllers for this adapter + int iNumControllers; + /// Number of displays for this adapter + int iNumDisplays; + /// Number of overlays for this adapter + int iNumOverlays; + /// Number of GLSyncConnectors + int iNumOfGLSyncConnectors; + /// The bit mask identifies the adapter caps + int iCapsMask; + /// The bit identifies the adapter caps \ref define_adapter_caps + int iCapsValue; + /// Number of Connectors for this adapter + int iNumConnectors; +}ADLAdapterCapsX2; + +typedef enum _ADL_ERROR_RECORD_SEVERITY +{ + ADL_GLOBALLY_UNCORRECTED = 1, + ADL_LOCALLY_UNCORRECTED = 2, + ADL_DEFFERRED = 3, + ADL_CORRECTED = 4 +}ADL_ERROR_RECORD_SEVERITY; + +typedef union _ADL_ECC_EDC_FLAG +{ + struct + { + unsigned int isEccAccessing : 1; + unsigned int reserved : 31; + }bits; + unsigned int u32All; +}ADL_ECC_EDC_FLAG; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about EDC Error Record +/// +/// This structure is used to store EDC Error Record +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLErrorRecord +{ + // Severity of error + ADL_ERROR_RECORD_SEVERITY Severity; + + // Is the counter valid? + int countValid; + + // Counter value, if valid + unsigned int count; + + // Is the location information valid? + int locationValid; + + // Physical location of error + unsigned int CU; // CU number on which error occurred, if known + char StructureName[32]; // e.g. LDS, TCC, etc. + + // Time of error record creation (e.g. time of query, or time of poison interrupt) + char tiestamp[32]; + + unsigned int padding[3]; +}ADLErrorRecord; + +typedef enum _ADL_EDC_BLOCK_ID +{ + ADL_EDC_BLOCK_ID_SQCIS = 1, + ADL_EDC_BLOCK_ID_SQCDS = 2, + ADL_EDC_BLOCK_ID_SGPR = 3, + ADL_EDC_BLOCK_ID_VGPR = 4, + ADL_EDC_BLOCK_ID_LDS = 5, + ADL_EDC_BLOCK_ID_GDS = 6, + ADL_EDC_BLOCK_ID_TCL1 = 7, + ADL_EDC_BLOCK_ID_TCL2 = 8 +}ADL_EDC_BLOCK_ID; + +typedef enum _ADL_ERROR_INJECTION_MODE +{ + ADL_ERROR_INJECTION_MODE_SINGLE = 1, + ADL_ERROR_INJECTION_MODE_MULTIPLE = 2, + ADL_ERROR_INJECTION_MODE_ADDRESS = 3 +}ADL_ERROR_INJECTION_MODE; + +typedef union _ADL_ERROR_PATTERN +{ + struct + { + unsigned long EccInjVector : 16; + unsigned long EccInjEn : 9; + unsigned long EccBeatEn : 4; + unsigned long EccChEn : 4; + unsigned long reserved : 31; + } bits; + unsigned long long u64Value; +} ADL_ERROR_PATTERN; + +typedef struct _ADL_ERROR_INJECTION_DATA +{ + unsigned long long errorAddress; + ADL_ERROR_PATTERN errorPattern; +}ADL_ERROR_INJECTION_DATA; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about EDC Error Injection +/// +/// This structure is used to store EDC Error Injection +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLErrorInjection +{ + ADL_EDC_BLOCK_ID blockId; + ADL_ERROR_INJECTION_MODE errorInjectionMode; +}ADLErrorInjection; + +typedef struct ADLErrorInjectionX2 +{ + ADL_EDC_BLOCK_ID blockId; + ADL_ERROR_INJECTION_MODE errorInjectionMode; + ADL_ERROR_INJECTION_DATA errorInjectionData; +}ADLErrorInjectionX2; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing per display FreeSync capability information. +/// +/// This structure is used to store the FreeSync capability of both the display and +/// the GPU the display is connected to. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLFreeSyncCap +{ + /// FreeSync capability flags. \ref define_freesync_caps + int iCaps; + /// Reports minimum FreeSync refresh rate supported by the display in micro hertz + int iMinRefreshRateInMicroHz; + /// Reports maximum FreeSync refresh rate supported by the display in micro hertz + int iMaxRefreshRateInMicroHz; + /// Reserved + int iReserved[5]; +} ADLFreeSyncCap; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing per display Display Connectivty Experience Settings +/// +/// This structure is used to store the Display Connectivity Experience settings of a +/// display +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLDceSettings +{ + DceSettingsType type; // Defines which structure is in the union below + union + { + struct + { + bool qualityDetectionEnabled; + } HdmiLq; + struct + { + DpLinkRate linkRate; // Read-only + unsigned int numberOfActiveLanes; // Read-only + unsigned int numberofTotalLanes; // Read-only + int relativePreEmphasis; // Allowable values are -2 to +2 + int relativeVoltageSwing; // Allowable values are -2 to +2 + int persistFlag; + } DpLink; + struct + { + bool linkProtectionEnabled; // Read-only + } Protection; + } Settings; + int iReserved[15]; +} ADLDceSettings; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Graphic Core +/// +/// This structure is used to get Graphic Core Info +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLGraphicCoreInfo +{ + /// indicate the graphic core generation + int iGCGen; + + union + { + /// Total number of CUs. Valid for GCN (iGCGen == GCN) + int iNumCUs; + /// Total number of WGPs. Valid for RDNA (iGCGen == RDNA) + int iNumWGPs; + }; + + union + { + /// Number of processing elements per CU. Valid for GCN (iGCGen == GCN) + int iNumPEsPerCU; + /// Number of processing elements per WGP. Valid for RDNA (iGCGen == RDNA) + int iNumPEsPerWGP; + }; + + /// Total number of SIMDs. Valid for Pre GCN (iGCGen == Pre-GCN) + int iNumSIMDs; + + /// Total number of ROPs. Valid for both GCN and Pre GCN + int iNumROPs; + + /// reserved for future use + int iReserved[11]; +}ADLGraphicCoreInfo; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive N clock range +/// +/// This structure is used to store information about Overdrive N clock range +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLODNParameterRange +{ + /// The starting value of the clock range + int iMode; + /// The starting value of the clock range + int iMin; + /// The ending value of the clock range + int iMax; + /// The minimum increment between clock values + int iStep; + /// The default clock values + int iDefault; + +} ADLODNParameterRange; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive N capabilities +/// +/// This structure is used to store information about Overdrive N capabilities +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLODNCapabilities +{ + /// Number of levels which describe the minimum to maximum clock ranges. + /// The 1st level indicates the minimum clocks, and the 2nd level + /// indicates the maximum clocks. + int iMaximumNumberOfPerformanceLevels; + /// Contains the hard limits of the sclk range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange sEngineClockRange; + /// Contains the hard limits of the mclk range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange sMemoryClockRange; + /// Contains the hard limits of the vddc range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange svddcRange; + /// Contains the hard limits of the power range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange power; + /// Contains the hard limits of the power range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange powerTuneTemperature; + /// Contains the hard limits of the Temperature range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange fanTemperature; + /// Contains the hard limits of the Fan range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange fanSpeed; + /// Contains the hard limits of the Fan range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange minimumPerformanceClock; +} ADLODNCapabilities; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive N capabilities +/// +/// This structure is used to store information about Overdrive N capabilities +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLODNCapabilitiesX2 +{ + /// Number of levels which describe the minimum to maximum clock ranges. + /// The 1st level indicates the minimum clocks, and the 2nd level + /// indicates the maximum clocks. + int iMaximumNumberOfPerformanceLevels; + /// bit vector, which tells what are the features are supported. + /// \ref: ADLODNFEATURECONTROL + int iFlags; + /// Contains the hard limits of the sclk range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange sEngineClockRange; + /// Contains the hard limits of the mclk range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange sMemoryClockRange; + /// Contains the hard limits of the vddc range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange svddcRange; + /// Contains the hard limits of the power range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange power; + /// Contains the hard limits of the power range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange powerTuneTemperature; + /// Contains the hard limits of the Temperature range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange fanTemperature; + /// Contains the hard limits of the Fan range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange fanSpeed; + /// Contains the hard limits of the Fan range. Overdrive + /// clocks cannot be set outside this range. + ADLODNParameterRange minimumPerformanceClock; + /// Contains the hard limits of the throttleNotification + ADLODNParameterRange throttleNotificaion; + /// Contains the hard limits of the Auto Systemclock + ADLODNParameterRange autoSystemClock; +} ADLODNCapabilitiesX2; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive level. +/// +/// This structure is used to store information about Overdrive level. +/// This structure is used by ADLODPerformanceLevels. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODNPerformanceLevel +{ + /// clock. + int iClock; + /// VDCC. + int iVddc; + /// enabled + int iEnabled; +} ADLODNPerformanceLevel; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive N performance levels. +/// +/// This structure is used to store information about Overdrive performance levels. +/// This structure is used by the ADL_OverdriveN_ODPerformanceLevels_Get() and ADL_OverdriveN_ODPerformanceLevels_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODNPerformanceLevels +{ + int iSize; + //Automatic/manual + int iMode; + /// Must be set to sizeof( \ref ADLODPerformanceLevels ) + sizeof( \ref ADLODPerformanceLevel ) * (ADLODParameters.iNumberOfPerformanceLevels - 1) + int iNumberOfPerformanceLevels; + /// Array of performance state descriptors. Must have ADLODParameters.iNumberOfPerformanceLevels elements. + ADLODNPerformanceLevel aLevels[1]; +} ADLODNPerformanceLevels; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive N Fan Speed. +/// +/// This structure is used to store information about Overdrive Fan control . +/// This structure is used by the ADL_OverdriveN_ODPerformanceLevels_Get() and ADL_OverdriveN_ODPerformanceLevels_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODNFanControl +{ + int iMode; + int iFanControlMode; + int iCurrentFanSpeedMode; + int iCurrentFanSpeed; + int iTargetFanSpeed; + int iTargetTemperature; + int iMinPerformanceClock; + int iMinFanLimit; +} ADLODNFanControl; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive N power limit. +/// +/// This structure is used to store information about Overdrive power limit. +/// This structure is used by the ADL_OverdriveN_ODPerformanceLevels_Get() and ADL_OverdriveN_ODPerformanceLevels_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODNPowerLimitSetting +{ + int iMode; + int iTDPLimit; + int iMaxOperatingTemperature; +} ADLODNPowerLimitSetting; + +typedef struct ADLODNPerformanceStatus +{ + int iCoreClock; + int iMemoryClock; + int iDCEFClock; + int iGFXClock; + int iUVDClock; + int iVCEClock; + int iGPUActivityPercent; + int iCurrentCorePerformanceLevel; + int iCurrentMemoryPerformanceLevel; + int iCurrentDCEFPerformanceLevel; + int iCurrentGFXPerformanceLevel; + int iUVDPerformanceLevel; + int iVCEPerformanceLevel; + int iCurrentBusSpeed; + int iCurrentBusLanes; + int iMaximumBusLanes; + int iVDDC; + int iVDDCI; +} ADLODNPerformanceStatus; + +///\brief Structure containing information about Overdrive level. +/// +/// This structure is used to store information about Overdrive level. +/// This structure is used by ADLODPerformanceLevels. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODNPerformanceLevelX2 +{ + /// clock. + int iClock; + /// VDCC. + int iVddc; + /// enabled + int iEnabled; + /// MASK + int iControl; +} ADLODNPerformanceLevelX2; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive N performance levels. +/// +/// This structure is used to store information about Overdrive performance levels. +/// This structure is used by the ADL_OverdriveN_ODPerformanceLevels_Get() and ADL_OverdriveN_ODPerformanceLevels_Set() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLODNPerformanceLevelsX2 +{ + int iSize; + //Automatic/manual + int iMode; + /// Must be set to sizeof( \ref ADLODPerformanceLevels ) + sizeof( \ref ADLODPerformanceLevel ) * (ADLODParameters.iNumberOfPerformanceLevels - 1) + int iNumberOfPerformanceLevels; + /// Array of performance state descriptors. Must have ADLODParameters.iNumberOfPerformanceLevels elements. + ADLODNPerformanceLevelX2 aLevels[1]; +} ADLODNPerformanceLevelsX2; + +typedef enum _ADLODNCurrentPowerType +{ + ODN_GPU_TOTAL_POWER = 0, + ODN_GPU_PPT_POWER, + ODN_GPU_SOCKET_POWER, + ODN_GPU_CHIP_POWER +} ADLODNCurrentPowerType; + +// in/out: CWDDEPM_CURRENTPOWERPARAMETERS +typedef struct _ADLODNCurrentPowerParameters +{ + int size; + ADLODNCurrentPowerType powerType; + int currentPower; +} ADLODNCurrentPowerParameters; + +//ODN Ext range data structure +typedef struct _ADLODNExtSingleInitSetting +{ + int mode; + int minValue; + int maxValue; + int step; + int defaultValue; +} ADLODNExtSingleInitSetting; + +//OD8 Ext range data structure +typedef struct _ADLOD8SingleInitSetting +{ + int featureID; + int minValue; + int maxValue; + int defaultValue; +} ADLOD8SingleInitSetting; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive8 initial setting +/// +/// This structure is used to store information about Overdrive8 initial setting +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD8InitSetting +{ + int count; + int overdrive8Capabilities; + ADLOD8SingleInitSetting od8SettingTable[OD8_COUNT]; +} ADLOD8InitSetting; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive8 current setting +/// +/// This structure is used to store information about Overdrive8 current setting +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLOD8CurrentSetting +{ + int count; + int Od8SettingTable[OD8_COUNT]; +} ADLOD8CurrentSetting; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Overdrive8 set setting +/// +/// This structure is used to store information about Overdrive8 set setting +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + +typedef struct _ADLOD8SingleSetSetting +{ + int value; + int requested; // 0 - default , 1 - requested + int reset; // 0 - do not reset , 1 - reset setting back to default +} ADLOD8SingleSetSetting; + + +typedef struct _ADLOD8SetSetting +{ + int count; + ADLOD8SingleSetSetting od8SettingTable[OD8_COUNT]; +} ADLOD8SetSetting; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about Performance Metrics data +/// +/// This structure is used to store information about Performance Metrics data output +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLSingleSensorData +{ + int supported; + int value; +} ADLSingleSensorData; + +typedef struct _ADLPMLogDataOutput +{ + int size; + ADLSingleSensorData sensors[ADL_PMLOG_MAX_SENSORS]; +}ADLPMLogDataOutput; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about PPLog settings. +/// +/// This structure is used to store information about PPLog settings. +/// This structure is used by the ADL2_PPLogSettings_Set() and ADL2_PPLogSettings_Get() functions. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct ADLPPLogSettings +{ + int BreakOnAssert; + int BreakOnWarn; + int LogEnabled; + int LogFieldMask; + int LogDestinations; + int LogSeverityEnabled; + int LogSourceMask; + int PowerProfilingEnabled; + int PowerProfilingTimeInterval; +}ADLPPLogSettings; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related Frames Per Second for AC and DC. +/// +/// This structure is used to store information related AC and DC Frames Per Second settings +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLFPSSettingsOutput +{ + /// size + int ulSize; + /// FPS Monitor is enabled in the AC state if 1 + int bACFPSEnabled; + /// FPS Monitor is enabled in the DC state if 1 + int bDCFPSEnabled; + /// Current Value of FPS Monitor in AC state + int ulACFPSCurrent; + /// Current Value of FPS Monitor in DC state + int ulDCFPSCurrent; + /// Maximum FPS Threshold allowed in PPLib for AC + int ulACFPSMaximum; + /// Minimum FPS Threshold allowed in PPLib for AC + int ulACFPSMinimum; + /// Maximum FPS Threshold allowed in PPLib for DC + int ulDCFPSMaximum; + /// Minimum FPS Threshold allowed in PPLib for DC + int ulDCFPSMinimum; + +} ADLFPSSettingsOutput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related Frames Per Second for AC and DC. +/// +/// This structure is used to store information related AC and DC Frames Per Second settings +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLFPSSettingsInput +{ + /// size + int ulSize; + /// Settings are for Global FPS (used by CCC) + int bGlobalSettings; + /// Current Value of FPS Monitor in AC state + int ulACFPSCurrent; + /// Current Value of FPS Monitor in DC state + int ulDCFPSCurrent; + /// Reserved + int ulReserved[6]; + +} ADLFPSSettingsInput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related power management logging. +/// +/// This structure is used to store support information for power management logging. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +enum { ADL_PMLOG_MAX_SUPPORTED_SENSORS = 256 }; + +typedef struct _ADLPMLogSupportInfo +{ + /// list of sensors defined by ADL_PMLOG_SENSORS + unsigned short usSensors[ADL_PMLOG_MAX_SUPPORTED_SENSORS]; + /// Reserved + int ulReserved[16]; + +} ADLPMLogSupportInfo; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information to start power management logging. +/// +/// This structure is used as input to ADL2_Adapter_PMLog_Start +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLPMLogStartInput +{ + /// list of sensors defined by ADL_PMLOG_SENSORS + unsigned short usSensors[ADL_PMLOG_MAX_SUPPORTED_SENSORS]; + /// Sample rate in milliseconds + unsigned long ulSampleRate; + /// Reserved + int ulReserved[15]; + +} ADLPMLogStartInput; + +typedef struct _ADLPMLogData +{ + /// Structure version + unsigned int ulVersion; + /// Current driver sample rate + unsigned int ulActiveSampleRate; + /// Timestamp of last update + unsigned long long ulLastUpdated; + /// 2D array of senesor and values + unsigned int ulValues[ADL_PMLOG_MAX_SUPPORTED_SENSORS][2]; + /// Reserved + unsigned int ulReserved[256]; + +} ADLPMLogData; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information to start power management logging. +/// +/// This structure is returned as output from ADL2_Adapter_PMLog_Start +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLPMLogStartOutput +{ + /// Pointer to memory address containing logging data + union + { + void* pLoggingAddress; + unsigned long long ptr_LoggingAddress; + }; + /// Reserved + int ulReserved[14]; + +} ADLPMLogStartOutput; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Get Error Counts Information +/// +/// This structure is used to store RAS Error Counts Get Input Information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + +typedef struct _ADLRASGetErrorCountsInput +{ + unsigned int Reserved[16]; +} ADLRASGetErrorCountsInput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Get Error Counts Information +/// +/// This structure is used to store RAS Error Counts Get Output Information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + + +typedef struct _ADLRASGetErrorCountsOutput +{ + unsigned int CorrectedErrors; // includes both DRAM and SRAM ECC + unsigned int UnCorrectedErrors; // includes both DRAM and SRAM ECC + unsigned int Reserved[14]; +} ADLRASGetErrorCountsOutput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Get Error Counts Information +/// +/// This structure is used to store RAS Error Counts Get Information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + +typedef struct _ADLRASGetErrorCounts +{ + unsigned int InputSize; + ADLRASGetErrorCountsInput Input; + unsigned int OutputSize; + ADLRASGetErrorCountsOutput Output; +} ADLRASGetErrorCounts; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Error Counts Reset Information +/// +/// This structure is used to store RAS Error Counts Reset Input Information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + + +typedef struct _ADLRASResetErrorCountsInput +{ + unsigned int Reserved[8]; +} ADLRASResetErrorCountsInput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Error Counts Reset Information +/// +/// This structure is used to store RAS Error Counts Reset Output Information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + + +typedef struct _ADLRASResetErrorCountsOutput +{ + unsigned int Reserved[8]; +} ADLRASResetErrorCountsOutput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Error Counts Reset Information +/// +/// This structure is used to store RAS Error Counts Reset Information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + + +typedef struct _ADLRASResetErrorCounts +{ + unsigned int InputSize; + ADLRASResetErrorCountsInput Input; + unsigned int OutputSize; + ADLRASResetErrorCountsOutput Output; +} ADLRASResetErrorCounts; + + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Error Injection information +/// +/// This structure is used to store RAS Error Injection input information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + +typedef struct _ADLRASErrorInjectonInput +{ + unsigned long long Address; + ADL_RAS_INJECTION_METHOD Value; + ADL_RAS_BLOCK_ID BlockId; + ADL_RAS_ERROR_TYPE InjectErrorType; + ADL_MEM_SUB_BLOCK_ID SubBlockIndex; + unsigned int padding[9]; +} ADLRASErrorInjectonInput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Error Injection information +/// +/// This structure is used to store RAS Error Injection output information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + + +typedef struct _ADLRASErrorInjectionOutput +{ + unsigned int ErrorInjectionStatus; + unsigned int padding[15]; +} ADLRASErrorInjectionOutput; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related RAS Error Injection information +/// +/// This structure is used to store RAS Error Injection information +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// + + +typedef struct _ADLRASErrorInjection +{ + unsigned int InputSize; + ADLRASErrorInjectonInput Input; + unsigned int OutputSize; + ADLRASErrorInjectionOutput Output; +} ADLRASErrorInjection; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about an application +/// +/// This structure is used to store basic information of a recently ran or currently running application +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADLSGApplicationInfo +{ + /// Application file name + wchar_t strFileName[ADL_MAX_PATH]; + /// Application file path + wchar_t strFilePath[ADL_MAX_PATH]; + /// Application version + wchar_t strVersion[ADL_MAX_PATH]; + /// Timestamp at which application has run + long long int timeStamp; + /// Holds whether the applicaition profile exists or not + unsigned int iProfileExists; + /// The GPU on which application runs + unsigned int iGPUAffinity; + /// The BDF of the GPU on which application runs + ADLBdf GPUBdf; +} ADLSGApplicationInfo; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information related Frames Per Second for AC and DC. +/// +/// This structure is used to store information related AC and DC Frames Per Second settings +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +enum { ADLPreFlipPostProcessingInfoInvalidLUTIndex = 0xFFFFFFFF }; + +enum ADLPreFlipPostProcessingLUTAlgorithm +{ + ADLPreFlipPostProcessingLUTAlgorithm_Default = 0, + ADLPreFlipPostProcessingLUTAlgorithm_Full, + ADLPreFlipPostProcessingLUTAlgorithm_Approximation +}; + +typedef struct _ADLPreFlipPostProcessingInfo +{ + /// size + int ulSize; + /// Current active state + int bEnabled; + /// Current selected LUT index. 0xFFFFFFF returned if nothing selected. + int ulSelectedLUTIndex; + /// Current selected LUT Algorithm + int ulSelectedLUTAlgorithm; + /// Reserved + int ulReserved[12]; + +} ADLPreFlipPostProcessingInfo; + + + +typedef struct _ADL_ERROR_REASON +{ + int boost; //ON, when boost is Enabled + int delag; //ON, when delag is Enabled + int chill; //ON, when chill is Enabled +}ADL_ERROR_REASON; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about DELAG Settings change reason +/// +/// Elements of DELAG settings changed reason. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADL_DELAG_NOTFICATION_REASON +{ + int HotkeyChanged; //Set when Hotkey value is changed + int GlobalEnableChanged; //Set when Global enable value is changed + int GlobalLimitFPSChanged; //Set when Global enable value is changed +}ADL_DELAG_NOTFICATION_REASON; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about DELAG Settings +/// +/// Elements of DELAG settings. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADL_DELAG_SETTINGS +{ + int Hotkey; // Hotkey value + int GlobalEnable; //Global enable value + int GlobalLimitFPS; //Global Limit FPS + int GlobalLimitFPS_MinLimit; //Gloabl Limit FPS slider min limit value + int GlobalLimitFPS_MaxLimit; //Gloabl Limit FPS slider max limit value + int GlobalLimitFPS_Step; //Gloabl Limit FPS step value +}ADL_DELAG_SETTINGS; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about BOOST Settings change reason +/// +/// Elements of BOOST settings changed reason. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADL_BOOST_NOTFICATION_REASON +{ + int HotkeyChanged; //Set when Hotkey value is changed + int GlobalEnableChanged; //Set when Global enable value is changed + int GlobalMinResChanged; //Set when Global min resolution value is changed +}ADL_BOOST_NOTFICATION_REASON; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about BOOST Settings +/// +/// Elements of BOOST settings. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADL_BOOST_SETTINGS +{ + int Hotkey; // Hotkey value + int GlobalEnable; //Global enable value + int GlobalMinRes; //Gloabl Min Resolution value + int GlobalMinRes_MinLimit; //Gloabl Min Resolution slider min limit value + int GlobalMinRes_MaxLimit; //Gloabl Min Resolution slider max limit value + int GlobalMinRes_Step; //Gloabl Min Resolution step value +}ADL_BOOST_SETTINGS; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about RIS Settings change reason +/// +/// Elements of RIS settings changed reason. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADL_RIS_NOTFICATION_REASON +{ + unsigned int GlobalEnableChanged; //Set when Global enable value is changed + unsigned int GlobalSharpeningDegreeChanged; //Set when Global sharpening Degree value is changed +}ADL_RIS_NOTFICATION_REASON; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about RIS Settings +/// +/// Elements of RIS settings. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADL_RIS_SETTINGS +{ + int GlobalEnable; //Global enable value + int GlobalSharpeningDegree; //Global sharpening value + int GlobalSharpeningDegree_MinLimit; //Gloabl sharpening slider min limit value + int GlobalSharpeningDegree_MaxLimit; //Gloabl sharpening slider max limit value + int GlobalSharpeningDegree_Step; //Gloabl sharpening step value +}ADL_RIS_SETTINGS; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about CHILL Settings change reason +/// +/// Elements of Chiil settings changed reason. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADL_CHILL_NOTFICATION_REASON +{ + int HotkeyChanged; //Set when Hotkey value is changed + int GlobalEnableChanged; //Set when Global enable value is changed + int GlobalMinFPSChanged; //Set when Global min FPS value is changed + int GlobalMaxFPSChanged; //Set when Global max FPS value is changed +}ADL_CHILL_NOTFICATION_REASON; + +///////////////////////////////////////////////////////////////////////////////////////////// +///\brief Structure containing information about CHILL Settings +/// +/// Elements of Chiil settings. +/// \nosubgrouping +//////////////////////////////////////////////////////////////////////////////////////////// +typedef struct _ADL_CHILL_SETTINGS +{ + int Hotkey; // Hotkey value + int GlobalEnable; //Global enable value + int GlobalMinFPS; //Global Min FPS value + int GlobalMaxFPS; //Global Max FPS value + int GlobalFPS_MinLimit; //Gloabl FPS slider min limit value + int GlobalFPS_MaxLimit; //Gloabl FPS slider max limit value + int GlobalFPS_Step; //Gloabl FPS Slider step value +}ADL_CHILL_SETTINGS; +#endif /* ADL_STRUCTURES_H_ */ diff --git a/src/3rdparty/argon2/CMakeLists.txt b/src/3rdparty/argon2/CMakeLists.txt index 0217382a..a9751fd9 100644 --- a/src/3rdparty/argon2/CMakeLists.txt +++ b/src/3rdparty/argon2/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.8) +cmake_minimum_required(VERSION 3.10) project(argon2 C) set(CMAKE_C_STANDARD 99) @@ -17,7 +17,7 @@ set(ARGON2_SOURCES set(ARGON2_X86_64_ENABLED ON) set(ARGON2_X86_64_LIBS argon2-sse2 argon2-ssse3 argon2-xop argon2-avx2 argon2-avx512f) -set(ARGON2_X86_64_SOURCES arch/x86_64/lib/argon2-arch.c arch/x86_64/lib/cpu-flags.c) +set(ARGON2_X86_64_SOURCES arch/x86_64/lib/argon2-arch.c) if (CMAKE_C_COMPILER_ID MATCHES MSVC) function(add_feature_impl FEATURE MSVC_FLAG DEF) diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-arch.c b/src/3rdparty/argon2/arch/x86_64/lib/argon2-arch.c index 4486e395..b5f0b5e2 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-arch.c +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-arch.c @@ -4,7 +4,6 @@ #include "impl-select.h" -#include "cpu-flags.h" #include "argon2-sse2.h" #include "argon2-ssse3.h" #include "argon2-xop.h" @@ -26,16 +25,14 @@ void fill_segment_default(const argon2_instance_t *instance, void argon2_get_impl_list(argon2_impl_list *list) { static const argon2_impl IMPLS[] = { - { "x86_64", NULL, fill_segment_default }, - { "SSE2", check_sse2, fill_segment_sse2 }, - { "SSSE3", check_ssse3, fill_segment_ssse3 }, - { "XOP", check_xop, fill_segment_xop }, - { "AVX2", check_avx2, fill_segment_avx2 }, - { "AVX-512F", check_avx512f, fill_segment_avx512f }, + { "x86_64", NULL, fill_segment_default }, + { "SSE2", xmrig_ar2_check_sse2, xmrig_ar2_fill_segment_sse2 }, + { "SSSE3", xmrig_ar2_check_ssse3, xmrig_ar2_fill_segment_ssse3 }, + { "XOP", xmrig_ar2_check_xop, xmrig_ar2_fill_segment_xop }, + { "AVX2", xmrig_ar2_check_avx2, xmrig_ar2_fill_segment_avx2 }, + { "AVX-512F", xmrig_ar2_check_avx512f, xmrig_ar2_fill_segment_avx512f }, }; - cpu_flags_get(); - list->count = sizeof(IMPLS) / sizeof(IMPLS[0]); list->entries = IMPLS; } diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx2.c b/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx2.c index 09ef421a..c8bf56f5 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx2.c +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx2.c @@ -9,8 +9,6 @@ # include #endif -#include "cpu-flags.h" - #define r16 (_mm256_setr_epi8( \ 2, 3, 4, 5, 6, 7, 0, 1, \ 10, 11, 12, 13, 14, 15, 8, 9, \ @@ -225,8 +223,7 @@ static void next_addresses(block *address_block, block *input_block) fill_block(zero2_block, address_block, address_block, 0); } -void fill_segment_avx2(const argon2_instance_t *instance, - argon2_position_t position) +void xmrig_ar2_fill_segment_avx2(const argon2_instance_t *instance, argon2_position_t position) { block *ref_block = NULL, *curr_block = NULL; block address_block, input_block; @@ -310,8 +307,7 @@ void fill_segment_avx2(const argon2_instance_t *instance, * lane. */ position.index = i; - ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, - ref_lane == position.lane); + ref_index = xmrig_ar2_index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, ref_lane == position.lane); /* 2 Creating a new block */ ref_block = @@ -327,21 +323,13 @@ void fill_segment_avx2(const argon2_instance_t *instance, } } -int check_avx2(void) -{ - return cpu_flags_have_avx2(); -} + +extern int cpu_flags_has_avx2(void); +int xmrig_ar2_check_avx2(void) { return cpu_flags_has_avx2(); } #else -void fill_segment_avx2(const argon2_instance_t *instance, - argon2_position_t position) -{ -} - -int check_avx2(void) -{ - return 0; -} +void xmrig_ar2_fill_segment_avx2(const argon2_instance_t *instance, argon2_position_t position) {} +int xmrig_ar2_check_avx2(void) { return 0; } #endif diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx2.h b/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx2.h index 8abdb8a5..2c34269a 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx2.h +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx2.h @@ -3,9 +3,7 @@ #include "core.h" -void fill_segment_avx2(const argon2_instance_t *instance, - argon2_position_t position); - -int check_avx2(void); +void xmrig_ar2_fill_segment_avx2(const argon2_instance_t *instance, argon2_position_t position); +int xmrig_ar2_check_avx2(void); #endif // ARGON2_AVX2_H diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx512f.c b/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx512f.c index 79fd2dda..f9df1b87 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx512f.c +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx512f.c @@ -10,8 +10,6 @@ # include #endif -#include "cpu-flags.h" - #define ror64(x, n) _mm512_ror_epi64((x), (n)) static __m512i f(__m512i x, __m512i y) @@ -210,8 +208,7 @@ static void next_addresses(block *address_block, block *input_block) fill_block(zero2_block, address_block, address_block, 0); } -void fill_segment_avx512f(const argon2_instance_t *instance, - argon2_position_t position) +void xmrig_ar2_fill_segment_avx512f(const argon2_instance_t *instance, argon2_position_t position) { block *ref_block = NULL, *curr_block = NULL; block address_block, input_block; @@ -295,8 +292,7 @@ void fill_segment_avx512f(const argon2_instance_t *instance, * lane. */ position.index = i; - ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, - ref_lane == position.lane); + ref_index = xmrig_ar2_index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, ref_lane == position.lane); /* 2 Creating a new block */ ref_block = @@ -312,21 +308,12 @@ void fill_segment_avx512f(const argon2_instance_t *instance, } } -int check_avx512f(void) -{ - return cpu_flags_have_avx512f(); -} +extern int cpu_flags_has_avx512f(void); +int xmrig_ar2_check_avx512f(void) { return cpu_flags_has_avx512f(); } #else -void fill_segment_avx512f(const argon2_instance_t *instance, - argon2_position_t position) -{ -} - -int check_avx512f(void) -{ - return 0; -} +void xmrig_ar2_fill_segment_avx512f(const argon2_instance_t *instance, argon2_position_t position) {} +int xmrig_ar2_check_avx512f(void) { return 0; } #endif diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx512f.h b/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx512f.h index ba431114..882bb7fd 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx512f.h +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-avx512f.h @@ -3,9 +3,7 @@ #include "core.h" -void fill_segment_avx512f(const argon2_instance_t *instance, - argon2_position_t position); - -int check_avx512f(void); +void xmrig_ar2_fill_segment_avx512f(const argon2_instance_t *instance, argon2_position_t position); +int xmrig_ar2_check_avx512f(void); #endif // ARGON2_AVX512F_H diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-sse2.c b/src/3rdparty/argon2/arch/x86_64/lib/argon2-sse2.c index 5eccdf07..099f851f 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-sse2.c +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-sse2.c @@ -7,8 +7,6 @@ # include #endif -#include "cpu-flags.h" - #define ror64_16(x) \ _mm_shufflehi_epi16( \ _mm_shufflelo_epi16((x), _MM_SHUFFLE(0, 3, 2, 1)), \ @@ -102,27 +100,17 @@ static __m128i f(__m128i x, __m128i y) #include "argon2-template-128.h" -void fill_segment_sse2(const argon2_instance_t *instance, - argon2_position_t position) +void xmrig_ar2_fill_segment_sse2(const argon2_instance_t *instance, argon2_position_t position) { fill_segment_128(instance, position); } -int check_sse2(void) -{ - return cpu_flags_have_sse2(); -} +extern int cpu_flags_has_sse2(void); +int xmrig_ar2_check_sse2(void) { return cpu_flags_has_sse2(); } #else -void fill_segment_sse2(const argon2_instance_t *instance, - argon2_position_t position) -{ -} - -int check_sse2(void) -{ - return 0; -} +void xmrig_ar2_fill_segment_sse2(const argon2_instance_t *instance, argon2_position_t position) {} +int xmrig_ar2_check_sse2(void) { return 0; } #endif diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-sse2.h b/src/3rdparty/argon2/arch/x86_64/lib/argon2-sse2.h index 024d503d..9f92fbc6 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-sse2.h +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-sse2.h @@ -3,9 +3,7 @@ #include "core.h" -void fill_segment_sse2(const argon2_instance_t *instance, - argon2_position_t position); - -int check_sse2(void); +void xmrig_ar2_fill_segment_sse2(const argon2_instance_t *instance, argon2_position_t position); +int xmrig_ar2_check_sse2(void); #endif // ARGON2_SSE2_H diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-ssse3.c b/src/3rdparty/argon2/arch/x86_64/lib/argon2-ssse3.c index 86e9b3c9..58a022ca 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-ssse3.c +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-ssse3.c @@ -9,8 +9,6 @@ # include #endif -#include "cpu-flags.h" - #define r16 (_mm_setr_epi8( \ 2, 3, 4, 5, 6, 7, 0, 1, \ 10, 11, 12, 13, 14, 15, 8, 9)) @@ -114,27 +112,17 @@ static __m128i f(__m128i x, __m128i y) #include "argon2-template-128.h" -void fill_segment_ssse3(const argon2_instance_t *instance, - argon2_position_t position) +void xmrig_ar2_fill_segment_ssse3(const argon2_instance_t *instance, argon2_position_t position) { fill_segment_128(instance, position); } -int check_ssse3(void) -{ - return cpu_flags_have_ssse3(); -} +extern int cpu_flags_has_ssse3(void); +int xmrig_ar2_check_ssse3(void) { return cpu_flags_has_ssse3(); } #else -void fill_segment_ssse3(const argon2_instance_t *instance, - argon2_position_t position) -{ -} - -int check_ssse3(void) -{ - return 0; -} +void xmrig_ar2_fill_segment_ssse3(const argon2_instance_t *instance, argon2_position_t position) {} +int xmrig_ar2_check_ssse3(void) { return 0; } #endif diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-ssse3.h b/src/3rdparty/argon2/arch/x86_64/lib/argon2-ssse3.h index 139fdacc..7d0346c7 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-ssse3.h +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-ssse3.h @@ -3,9 +3,7 @@ #include "core.h" -void fill_segment_ssse3(const argon2_instance_t *instance, - argon2_position_t position); - -int check_ssse3(void); +void xmrig_ar2_fill_segment_ssse3(const argon2_instance_t *instance, argon2_position_t position); +int xmrig_ar2_check_ssse3(void); #endif // ARGON2_SSSE3_H diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-template-128.h b/src/3rdparty/argon2/arch/x86_64/lib/argon2-template-128.h index 4fb04c1f..e55bbb92 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-template-128.h +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-template-128.h @@ -150,8 +150,7 @@ static void fill_segment_128(const argon2_instance_t *instance, * lane. */ position.index = i; - ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, - ref_lane == position.lane); + ref_index = xmrig_ar2_index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, ref_lane == position.lane); /* 2 Creating a new block */ ref_block = diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-xop.c b/src/3rdparty/argon2/arch/x86_64/lib/argon2-xop.c index 0e877bce..6fc6aa4b 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-xop.c +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-xop.c @@ -9,8 +9,6 @@ # include #endif -#include "cpu-flags.h" - #define ror64(x, c) _mm_roti_epi64((x), -(c)) static __m128i f(__m128i x, __m128i y) @@ -102,27 +100,17 @@ static __m128i f(__m128i x, __m128i y) #include "argon2-template-128.h" -void fill_segment_xop(const argon2_instance_t *instance, - argon2_position_t position) +void xmrig_ar2_fill_segment_xop(const argon2_instance_t *instance, argon2_position_t position) { fill_segment_128(instance, position); } -int check_xop(void) -{ - return cpu_flags_have_xop(); -} +extern int cpu_flags_has_xop(void); +int xmrig_ar2_check_xop(void) { return cpu_flags_has_xop(); } #else -void fill_segment_xop(const argon2_instance_t *instance, - argon2_position_t position) -{ -} - -int check_xop(void) -{ - return 0; -} +void xmrig_ar2_fill_segment_xop(const argon2_instance_t *instance, argon2_position_t position) {} +int xmrig_ar2_check_xop(void) { return 0; } #endif diff --git a/src/3rdparty/argon2/arch/x86_64/lib/argon2-xop.h b/src/3rdparty/argon2/arch/x86_64/lib/argon2-xop.h index 1474a11c..631f239c 100644 --- a/src/3rdparty/argon2/arch/x86_64/lib/argon2-xop.h +++ b/src/3rdparty/argon2/arch/x86_64/lib/argon2-xop.h @@ -3,9 +3,7 @@ #include "core.h" -void fill_segment_xop(const argon2_instance_t *instance, - argon2_position_t position); - -int check_xop(void); +void xmrig_ar2_fill_segment_xop(const argon2_instance_t *instance, argon2_position_t position); +int xmrig_ar2_check_xop(void); #endif // ARGON2_XOP_H diff --git a/src/3rdparty/argon2/arch/x86_64/lib/cpu-flags.c b/src/3rdparty/argon2/arch/x86_64/lib/cpu-flags.c deleted file mode 100644 index cd13cb01..00000000 --- a/src/3rdparty/argon2/arch/x86_64/lib/cpu-flags.c +++ /dev/null @@ -1,129 +0,0 @@ -#include -#include - - -#include "cpu-flags.h" - -#include - -#ifdef _MSC_VER -# include -#else -# include -#endif - -#ifndef bit_OSXSAVE -# define bit_OSXSAVE (1 << 27) -#endif - -#ifndef bit_SSE2 -# define bit_SSE2 (1 << 26) -#endif - -#ifndef bit_SSSE3 -# define bit_SSSE3 (1 << 9) -#endif - -#ifndef bit_AVX2 -# define bit_AVX2 (1 << 5) -#endif - -#ifndef bit_AVX512F -# define bit_AVX512F (1 << 16) -#endif - -#ifndef bit_XOP -# define bit_XOP (1 << 11) -#endif - -#define PROCESSOR_INFO (1) -#define EXTENDED_FEATURES (7) - -#define EAX_Reg (0) -#define EBX_Reg (1) -#define ECX_Reg (2) -#define EDX_Reg (3) - - -enum { - X86_64_FEATURE_SSE2 = (1 << 0), - X86_64_FEATURE_SSSE3 = (1 << 1), - X86_64_FEATURE_XOP = (1 << 2), - X86_64_FEATURE_AVX2 = (1 << 3), - X86_64_FEATURE_AVX512F = (1 << 4), -}; - -static unsigned int cpu_flags; - - -static inline void cpuid(uint32_t level, int32_t output[4]) -{ -# ifdef _MSC_VER - __cpuid(output, (int) level); -# else - __cpuid_count(level, 0, output[0], output[1], output[2], output[3]); -# endif -} - - -static bool has_feature(uint32_t level, uint32_t reg, int32_t bit) -{ - int32_t cpu_info[4] = { 0 }; - cpuid(level, cpu_info); - - return (cpu_info[reg] & bit) != 0; -} - - -void cpu_flags_get(void) -{ - if (has_feature(PROCESSOR_INFO, EDX_Reg, bit_SSE2)) { - cpu_flags |= X86_64_FEATURE_SSE2; - } - - if (has_feature(PROCESSOR_INFO, ECX_Reg, bit_SSSE3)) { - cpu_flags |= X86_64_FEATURE_SSSE3; - } - - if (!has_feature(PROCESSOR_INFO, ECX_Reg, bit_OSXSAVE)) { - return; - } - - if (has_feature(EXTENDED_FEATURES, EBX_Reg, bit_AVX2)) { - cpu_flags |= X86_64_FEATURE_AVX2; - } - - if (has_feature(EXTENDED_FEATURES, EBX_Reg, bit_AVX512F)) { - cpu_flags |= X86_64_FEATURE_AVX512F; - } - - if (has_feature(0x80000001, ECX_Reg, bit_XOP)) { - cpu_flags |= X86_64_FEATURE_XOP; - } -} - -int cpu_flags_have_sse2(void) -{ - return cpu_flags & X86_64_FEATURE_SSE2; -} - -int cpu_flags_have_ssse3(void) -{ - return cpu_flags & X86_64_FEATURE_SSSE3; -} - -int cpu_flags_have_xop(void) -{ - return cpu_flags & X86_64_FEATURE_XOP; -} - -int cpu_flags_have_avx2(void) -{ - return cpu_flags & X86_64_FEATURE_AVX2; -} - -int cpu_flags_have_avx512f(void) -{ - return cpu_flags & X86_64_FEATURE_AVX512F; -} - diff --git a/src/3rdparty/argon2/arch/x86_64/lib/cpu-flags.h b/src/3rdparty/argon2/arch/x86_64/lib/cpu-flags.h deleted file mode 100644 index b546a8ba..00000000 --- a/src/3rdparty/argon2/arch/x86_64/lib/cpu-flags.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef ARGON2_CPU_FLAGS_H -#define ARGON2_CPU_FLAGS_H - -void cpu_flags_get(void); - -int cpu_flags_have_sse2(void); -int cpu_flags_have_ssse3(void); -int cpu_flags_have_xop(void); -int cpu_flags_have_avx2(void); -int cpu_flags_have_avx512f(void); - -#endif // ARGON2_CPU_FLAGS_H diff --git a/src/3rdparty/argon2/lib/argon2-template-64.h b/src/3rdparty/argon2/lib/argon2-template-64.h index 16ddbd35..c7541c07 100644 --- a/src/3rdparty/argon2/lib/argon2-template-64.h +++ b/src/3rdparty/argon2/lib/argon2-template-64.h @@ -174,8 +174,7 @@ static void fill_segment_64(const argon2_instance_t *instance, * lane. */ position.index = i; - ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, - ref_lane == position.lane); + ref_index = xmrig_ar2_index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, ref_lane == position.lane); /* 2 Creating a new block */ ref_block = diff --git a/src/3rdparty/argon2/lib/argon2.c b/src/3rdparty/argon2/lib/argon2.c index b2eafd2f..ab45229c 100644 --- a/src/3rdparty/argon2/lib/argon2.c +++ b/src/3rdparty/argon2/lib/argon2.c @@ -57,7 +57,7 @@ size_t argon2_memory_size(uint32_t m_cost, uint32_t parallelism) { int argon2_ctx_mem(argon2_context *context, argon2_type type, void *memory, size_t memory_size) { /* 1. Validate all inputs */ - int result = validate_inputs(context); + int result = xmrig_ar2_validate_inputs(context); uint32_t memory_blocks, segment_length; argon2_instance_t instance; @@ -98,20 +98,20 @@ int argon2_ctx_mem(argon2_context *context, argon2_type type, void *memory, /* 3. Initialization: Hashing inputs, allocating memory, filling first * blocks */ - result = initialize(&instance, context); + result = xmrig_ar2_initialize(&instance, context); if (ARGON2_OK != result) { return result; } /* 4. Filling memory */ - result = fill_memory_blocks(&instance); + result = xmrig_ar2_fill_memory_blocks(&instance); if (ARGON2_OK != result) { return result; } /* 5. Finalization */ - finalize(context, &instance); + xmrig_ar2_finalize(context, &instance); return ARGON2_OK; } @@ -174,7 +174,7 @@ int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, result = argon2_ctx(&context, type); if (result != ARGON2_OK) { - clear_internal_memory(out, hashlen); + xmrig_ar2_clear_internal_memory(out, hashlen); free(out); return result; } @@ -187,13 +187,13 @@ int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, /* if encoding requested, write it */ if (encoded && encodedlen) { if (encode_string(encoded, encodedlen, &context, type) != ARGON2_OK) { - clear_internal_memory(out, hashlen); /* wipe buffers if error */ - clear_internal_memory(encoded, encodedlen); + xmrig_ar2_clear_internal_memory(out, hashlen); /* wipe buffers if error */ + xmrig_ar2_clear_internal_memory(encoded, encodedlen); free(out); return ARGON2_ENCODING_FAIL; } } - clear_internal_memory(out, hashlen); + xmrig_ar2_clear_internal_memory(out, hashlen); free(out); return ARGON2_OK; diff --git a/src/3rdparty/argon2/lib/blake2/blake2.c b/src/3rdparty/argon2/lib/blake2/blake2.c index d32028ed..76de85a5 100644 --- a/src/3rdparty/argon2/lib/blake2/blake2.c +++ b/src/3rdparty/argon2/lib/blake2/blake2.c @@ -128,14 +128,14 @@ static void blake2b_init_state(blake2b_state *S) S->buflen = 0; } -void blake2b_init(blake2b_state *S, size_t outlen) +void xmrig_ar2_blake2b_init(blake2b_state *S, size_t outlen) { blake2b_init_state(S); /* XOR initial state with param block: */ S->h[0] ^= (uint64_t)outlen | (UINT64_C(1) << 16) | (UINT64_C(1) << 24); } -void blake2b_update(blake2b_state *S, const void *in, size_t inlen) +void xmrig_ar2_blake2b_update(blake2b_state *S, const void *in, size_t inlen) { const uint8_t *pin = (const uint8_t *)in; @@ -160,7 +160,7 @@ void blake2b_update(blake2b_state *S, const void *in, size_t inlen) S->buflen += inlen; } -void blake2b_final(blake2b_state *S, void *out, size_t outlen) +void xmrig_ar2_blake2b_final(blake2b_state *S, void *out, size_t outlen) { uint8_t buffer[BLAKE2B_OUTBYTES] = {0}; unsigned int i; @@ -174,12 +174,12 @@ void blake2b_final(blake2b_state *S, void *out, size_t outlen) } memcpy(out, buffer, outlen); - clear_internal_memory(buffer, sizeof(buffer)); - clear_internal_memory(S->buf, sizeof(S->buf)); - clear_internal_memory(S->h, sizeof(S->h)); + xmrig_ar2_clear_internal_memory(buffer, sizeof(buffer)); + xmrig_ar2_clear_internal_memory(S->buf, sizeof(S->buf)); + xmrig_ar2_clear_internal_memory(S->h, sizeof(S->h)); } -void blake2b_long(void *out, size_t outlen, const void *in, size_t inlen) +void xmrig_ar2_blake2b_long(void *out, size_t outlen, const void *in, size_t inlen) { uint8_t *pout = (uint8_t *)out; blake2b_state blake_state; @@ -187,39 +187,39 @@ void blake2b_long(void *out, size_t outlen, const void *in, size_t inlen) store32(outlen_bytes, (uint32_t)outlen); if (outlen <= BLAKE2B_OUTBYTES) { - blake2b_init(&blake_state, outlen); - blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes)); - blake2b_update(&blake_state, in, inlen); - blake2b_final(&blake_state, pout, outlen); + xmrig_ar2_blake2b_init(&blake_state, outlen); + xmrig_ar2_blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes)); + xmrig_ar2_blake2b_update(&blake_state, in, inlen); + xmrig_ar2_blake2b_final(&blake_state, pout, outlen); } else { uint32_t toproduce; uint8_t out_buffer[BLAKE2B_OUTBYTES]; - blake2b_init(&blake_state, BLAKE2B_OUTBYTES); - blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes)); - blake2b_update(&blake_state, in, inlen); - blake2b_final(&blake_state, out_buffer, BLAKE2B_OUTBYTES); + xmrig_ar2_blake2b_init(&blake_state, BLAKE2B_OUTBYTES); + xmrig_ar2_blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes)); + xmrig_ar2_blake2b_update(&blake_state, in, inlen); + xmrig_ar2_blake2b_final(&blake_state, out_buffer, BLAKE2B_OUTBYTES); memcpy(pout, out_buffer, BLAKE2B_OUTBYTES / 2); pout += BLAKE2B_OUTBYTES / 2; toproduce = (uint32_t)outlen - BLAKE2B_OUTBYTES / 2; while (toproduce > BLAKE2B_OUTBYTES) { - blake2b_init(&blake_state, BLAKE2B_OUTBYTES); - blake2b_update(&blake_state, out_buffer, BLAKE2B_OUTBYTES); - blake2b_final(&blake_state, out_buffer, BLAKE2B_OUTBYTES); + xmrig_ar2_blake2b_init(&blake_state, BLAKE2B_OUTBYTES); + xmrig_ar2_blake2b_update(&blake_state, out_buffer, BLAKE2B_OUTBYTES); + xmrig_ar2_blake2b_final(&blake_state, out_buffer, BLAKE2B_OUTBYTES); memcpy(pout, out_buffer, BLAKE2B_OUTBYTES / 2); pout += BLAKE2B_OUTBYTES / 2; toproduce -= BLAKE2B_OUTBYTES / 2; } - blake2b_init(&blake_state, toproduce); - blake2b_update(&blake_state, out_buffer, BLAKE2B_OUTBYTES); - blake2b_final(&blake_state, out_buffer, toproduce); + xmrig_ar2_blake2b_init(&blake_state, toproduce); + xmrig_ar2_blake2b_update(&blake_state, out_buffer, BLAKE2B_OUTBYTES); + xmrig_ar2_blake2b_final(&blake_state, out_buffer, toproduce); memcpy(pout, out_buffer, toproduce); - clear_internal_memory(out_buffer, sizeof(out_buffer)); + xmrig_ar2_clear_internal_memory(out_buffer, sizeof(out_buffer)); } } diff --git a/src/3rdparty/argon2/lib/blake2/blake2.h b/src/3rdparty/argon2/lib/blake2/blake2.h index 7deeaa1f..33f19eec 100644 --- a/src/3rdparty/argon2/lib/blake2/blake2.h +++ b/src/3rdparty/argon2/lib/blake2/blake2.h @@ -20,11 +20,11 @@ typedef struct __blake2b_state { } blake2b_state; /* Streaming API */ -void blake2b_init(blake2b_state *S, size_t outlen); -void blake2b_update(blake2b_state *S, const void *in, size_t inlen); -void blake2b_final(blake2b_state *S, void *out, size_t outlen); +void xmrig_ar2_blake2b_init(blake2b_state *S, size_t outlen); +void xmrig_ar2_blake2b_update(blake2b_state *S, const void *in, size_t inlen); +void xmrig_ar2_blake2b_final(blake2b_state *S, void *out, size_t outlen); -void blake2b_long(void *out, size_t outlen, const void *in, size_t inlen); +void xmrig_ar2_blake2b_long(void *out, size_t outlen, const void *in, size_t inlen); #endif // ARGON2_BLAKE2_H diff --git a/src/3rdparty/argon2/lib/core.c b/src/3rdparty/argon2/lib/core.c index 5d130c04..8c5d1c0e 100644 --- a/src/3rdparty/argon2/lib/core.c +++ b/src/3rdparty/argon2/lib/core.c @@ -77,8 +77,7 @@ static void store_block(void *output, const block *src) { /***************Memory functions*****************/ -int allocate_memory(const argon2_context *context, - argon2_instance_t *instance) { +int xmrig_ar2_allocate_memory(const argon2_context *context, argon2_instance_t *instance) { size_t blocks = instance->memory_blocks; size_t memory_size = blocks * ARGON2_BLOCK_SIZE; @@ -107,11 +106,10 @@ int allocate_memory(const argon2_context *context, return ARGON2_OK; } -void free_memory(const argon2_context *context, - const argon2_instance_t *instance) { +void xmrig_ar2_free_memory(const argon2_context *context, const argon2_instance_t *instance) { size_t memory_size = instance->memory_blocks * ARGON2_BLOCK_SIZE; - clear_internal_memory(instance->memory, memory_size); + xmrig_ar2_clear_internal_memory(instance->memory, memory_size); if (instance->keep_memory) { /* user-supplied memory -- do not free */ @@ -125,7 +123,7 @@ void free_memory(const argon2_context *context, } } -void NOT_OPTIMIZED secure_wipe_memory(void *v, size_t n) { +void NOT_OPTIMIZED xmrig_ar2_secure_wipe_memory(void *v, size_t n) { #if defined(_MSC_VER) && VC_GE_2005(_MSC_VER) SecureZeroMemory(v, n); #elif defined memset_s @@ -140,14 +138,14 @@ void NOT_OPTIMIZED secure_wipe_memory(void *v, size_t n) { /* Memory clear flag defaults to true. */ int FLAG_clear_internal_memory = 0; -void clear_internal_memory(void *v, size_t n) { +void xmrig_ar2_clear_internal_memory(void *v, size_t n) { if (FLAG_clear_internal_memory && v) { - secure_wipe_memory(v, n); + xmrig_ar2_secure_wipe_memory(v, n); } } -void finalize(const argon2_context *context, argon2_instance_t *instance) { - if (context != NULL && instance != NULL) { +void xmrig_ar2_finalize(const argon2_context *context, argon2_instance_t *instance) { + if (context != NULL && instance != NULL && context->out != NULL) { block blockhash; uint32_t l; @@ -164,24 +162,21 @@ void finalize(const argon2_context *context, argon2_instance_t *instance) { { uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE]; store_block(blockhash_bytes, &blockhash); - blake2b_long(context->out, context->outlen, blockhash_bytes, - ARGON2_BLOCK_SIZE); + xmrig_ar2_blake2b_long(context->out, context->outlen, blockhash_bytes, ARGON2_BLOCK_SIZE); /* clear blockhash and blockhash_bytes */ - clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE); - clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE); + xmrig_ar2_clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE); + xmrig_ar2_clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE); } if (instance->print_internals) { print_tag(context->out, context->outlen); } - free_memory(context, instance); + xmrig_ar2_free_memory(context, instance); } } -uint32_t index_alpha(const argon2_instance_t *instance, - const argon2_position_t *position, uint32_t pseudo_rand, - int same_lane) { +uint32_t xmrig_ar2_index_alpha(const argon2_instance_t *instance, const argon2_position_t *position, uint32_t pseudo_rand, int same_lane) { /* * Pass 0: * This lane : all already finished segments plus already constructed @@ -257,7 +252,7 @@ static int fill_memory_blocks_st(argon2_instance_t *instance) { for (s = 0; s < ARGON2_SYNC_POINTS; ++s) { for (l = 0; l < instance->lanes; ++l) { argon2_position_t position = { r, l, (uint8_t)s, 0 }; - fill_segment(instance, position); + xmrig_ar2_fill_segment(instance, position); } } @@ -268,7 +263,7 @@ static int fill_memory_blocks_st(argon2_instance_t *instance) { return ARGON2_OK; } -int fill_memory_blocks(argon2_instance_t *instance) { +int xmrig_ar2_fill_memory_blocks(argon2_instance_t *instance) { if (instance == NULL || instance->lanes == 0) { return ARGON2_INCORRECT_PARAMETER; } @@ -276,19 +271,19 @@ int fill_memory_blocks(argon2_instance_t *instance) { return fill_memory_blocks_st(instance); } -int validate_inputs(const argon2_context *context) { +int xmrig_ar2_validate_inputs(const argon2_context *context) { if (NULL == context) { return ARGON2_INCORRECT_PARAMETER; } - if (NULL == context->out) { - return ARGON2_OUTPUT_PTR_NULL; - } + //if (NULL == context->out) { + // return ARGON2_OUTPUT_PTR_NULL; + //} /* Validate output length */ - if (ARGON2_MIN_OUTLEN > context->outlen) { - return ARGON2_OUTPUT_TOO_SHORT; - } + //if (ARGON2_MIN_OUTLEN > context->outlen) { + // return ARGON2_OUTPUT_TOO_SHORT; + //} if (ARGON2_MAX_OUTLEN < context->outlen) { return ARGON2_OUTPUT_TOO_LONG; @@ -403,7 +398,7 @@ int validate_inputs(const argon2_context *context) { return ARGON2_OK; } -void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance) { +void xmrig_ar2_fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance) { uint32_t l; /* Make the first and second block in each lane as G(H0||0||i) or G(H0||1||i) */ @@ -412,21 +407,17 @@ void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance) { store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 0); store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH + 4, l); - blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash, - ARGON2_PREHASH_SEED_LENGTH); - load_block(&instance->memory[l * instance->lane_length + 0], - blockhash_bytes); + xmrig_ar2_blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash, ARGON2_PREHASH_SEED_LENGTH); + load_block(&instance->memory[l * instance->lane_length + 0], blockhash_bytes); store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 1); - blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash, - ARGON2_PREHASH_SEED_LENGTH); - load_block(&instance->memory[l * instance->lane_length + 1], - blockhash_bytes); + xmrig_ar2_blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash, ARGON2_PREHASH_SEED_LENGTH); + load_block(&instance->memory[l * instance->lane_length + 1], blockhash_bytes); } - clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE); + xmrig_ar2_clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE); } -void initial_hash(uint8_t *blockhash, argon2_context *context, +void xmrig_ar2_initial_hash(uint8_t *blockhash, argon2_context *context, argon2_type type) { blake2b_state BlakeHash; uint8_t value[sizeof(uint32_t)]; @@ -435,72 +426,70 @@ void initial_hash(uint8_t *blockhash, argon2_context *context, return; } - blake2b_init(&BlakeHash, ARGON2_PREHASH_DIGEST_LENGTH); + xmrig_ar2_blake2b_init(&BlakeHash, ARGON2_PREHASH_DIGEST_LENGTH); store32(&value, context->lanes); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); store32(&value, context->outlen); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); store32(&value, context->m_cost); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); store32(&value, context->t_cost); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); store32(&value, context->version); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); store32(&value, (uint32_t)type); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); store32(&value, context->pwdlen); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); if (context->pwd != NULL) { - blake2b_update(&BlakeHash, (const uint8_t *)context->pwd, + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)context->pwd, context->pwdlen); if (context->flags & ARGON2_FLAG_CLEAR_PASSWORD) { - secure_wipe_memory(context->pwd, context->pwdlen); + xmrig_ar2_secure_wipe_memory(context->pwd, context->pwdlen); context->pwdlen = 0; } } store32(&value, context->saltlen); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); if (context->salt != NULL) { - blake2b_update(&BlakeHash, (const uint8_t *)context->salt, + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)context->salt, context->saltlen); } store32(&value, context->secretlen); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); if (context->secret != NULL) { - blake2b_update(&BlakeHash, (const uint8_t *)context->secret, - context->secretlen); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)context->secret, context->secretlen); if (context->flags & ARGON2_FLAG_CLEAR_SECRET) { - secure_wipe_memory(context->secret, context->secretlen); + xmrig_ar2_secure_wipe_memory(context->secret, context->secretlen); context->secretlen = 0; } } store32(&value, context->adlen); - blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); if (context->ad != NULL) { - blake2b_update(&BlakeHash, (const uint8_t *)context->ad, - context->adlen); + xmrig_ar2_blake2b_update(&BlakeHash, (const uint8_t *)context->ad, context->adlen); } - blake2b_final(&BlakeHash, blockhash, ARGON2_PREHASH_DIGEST_LENGTH); + xmrig_ar2_blake2b_final(&BlakeHash, blockhash, ARGON2_PREHASH_DIGEST_LENGTH); } -int initialize(argon2_instance_t *instance, argon2_context *context) { +int xmrig_ar2_initialize(argon2_instance_t *instance, argon2_context *context) { uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; int result = ARGON2_OK; @@ -510,7 +499,7 @@ int initialize(argon2_instance_t *instance, argon2_context *context) { /* 1. Memory allocation */ - result = allocate_memory(context, instance); + result = xmrig_ar2_allocate_memory(context, instance); if (result != ARGON2_OK) { return result; } @@ -519,11 +508,9 @@ int initialize(argon2_instance_t *instance, argon2_context *context) { /* H_0 + 8 extra bytes to produce the first blocks */ /* uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; */ /* Hashing all inputs */ - initial_hash(blockhash, context, instance->type); + xmrig_ar2_initial_hash(blockhash, context, instance->type); /* Zeroing 8 extra bytes */ - clear_internal_memory(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, - ARGON2_PREHASH_SEED_LENGTH - - ARGON2_PREHASH_DIGEST_LENGTH); + xmrig_ar2_clear_internal_memory(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, ARGON2_PREHASH_SEED_LENGTH - ARGON2_PREHASH_DIGEST_LENGTH); if (instance->print_internals) { initial_kat(blockhash, context, instance->type); @@ -531,9 +518,9 @@ int initialize(argon2_instance_t *instance, argon2_context *context) { /* 3. Creating first blocks, we always have at least two blocks in a slice */ - fill_first_blocks(blockhash, instance); + xmrig_ar2_fill_first_blocks(blockhash, instance); /* Clearing the hash */ - clear_internal_memory(blockhash, ARGON2_PREHASH_SEED_LENGTH); + xmrig_ar2_clear_internal_memory(blockhash, ARGON2_PREHASH_SEED_LENGTH); return ARGON2_OK; } diff --git a/src/3rdparty/argon2/lib/core.h b/src/3rdparty/argon2/lib/core.h index 8a3227a9..1fc75bcc 100644 --- a/src/3rdparty/argon2/lib/core.h +++ b/src/3rdparty/argon2/lib/core.h @@ -110,8 +110,7 @@ typedef struct Argon2_thread_data { * @param instance the Argon2 instance * @return ARGON2_OK if memory is allocated successfully */ -int allocate_memory(const argon2_context *context, - argon2_instance_t *instance); +int xmrig_ar2_allocate_memory(const argon2_context *context, argon2_instance_t *instance); /* * Frees memory at the given pointer, uses the appropriate deallocator as @@ -119,22 +118,21 @@ int allocate_memory(const argon2_context *context, * @param context argon2_context which specifies the deallocator * @param instance the Argon2 instance */ -void free_memory(const argon2_context *context, - const argon2_instance_t *instance); +void xmrig_ar2_free_memory(const argon2_context *context, const argon2_instance_t *instance); /* Function that securely cleans the memory. This ignores any flags set * regarding clearing memory. Usually one just calls clear_internal_memory. * @param mem Pointer to the memory * @param s Memory size in bytes */ -void secure_wipe_memory(void *v, size_t n); +void xmrig_ar2_secure_wipe_memory(void *v, size_t n); /* Function that securely clears the memory if FLAG_clear_internal_memory is * set. If the flag isn't set, this function does nothing. * @param mem Pointer to the memory * @param s Memory size in bytes */ -ARGON2_PUBLIC void clear_internal_memory(void *v, size_t n); +ARGON2_PUBLIC void xmrig_ar2_clear_internal_memory(void *v, size_t n); /* * Computes absolute position of reference block in the lane following a skewed @@ -146,9 +144,7 @@ ARGON2_PUBLIC void clear_internal_memory(void *v, size_t n); * If so we can reference the current segment * @pre All pointers must be valid */ -uint32_t index_alpha(const argon2_instance_t *instance, - const argon2_position_t *position, uint32_t pseudo_rand, - int same_lane); +uint32_t xmrig_ar2_index_alpha(const argon2_instance_t *instance, const argon2_position_t *position, uint32_t pseudo_rand, int same_lane); /* * Function that validates all inputs against predefined restrictions and return @@ -157,7 +153,7 @@ uint32_t index_alpha(const argon2_instance_t *instance, * @return ARGON2_OK if everything is all right, otherwise one of error codes * (all defined in */ -int validate_inputs(const argon2_context *context); +int xmrig_ar2_validate_inputs(const argon2_context *context); /* * Hashes all the inputs into @a blockhash[PREHASH_DIGEST_LENGTH], clears @@ -169,8 +165,7 @@ int validate_inputs(const argon2_context *context); * @pre @a blockhash must have at least @a PREHASH_DIGEST_LENGTH bytes * allocated */ -void initial_hash(uint8_t *blockhash, argon2_context *context, - argon2_type type); +void xmrig_ar2_initial_hash(uint8_t *blockhash, argon2_context *context, argon2_type type); /* * Function creates first 2 blocks per lane @@ -178,7 +173,7 @@ void initial_hash(uint8_t *blockhash, argon2_context *context, * @param blockhash Pointer to the pre-hashing digest * @pre blockhash must point to @a PREHASH_SEED_LENGTH allocated values */ -void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance); +void xmrig_ar2_fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance); /* * Function allocates memory, hashes the inputs with Blake, and creates first @@ -190,7 +185,7 @@ void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance); * @return Zero if successful, -1 if memory failed to allocate. @context->state * will be modified if successful. */ -int initialize(argon2_instance_t *instance, argon2_context *context); +int xmrig_ar2_initialize(argon2_instance_t *instance, argon2_context *context); /* * XORing the last block of each lane, hashing it, making the tag. Deallocates @@ -203,7 +198,7 @@ int initialize(argon2_instance_t *instance, argon2_context *context); * @pre if context->free_cbk is not NULL, it should point to a function that * deallocates memory */ -void finalize(const argon2_context *context, argon2_instance_t *instance); +void xmrig_ar2_finalize(const argon2_context *context, argon2_instance_t *instance); /* * Function that fills the segment using previous segments also from other @@ -212,8 +207,7 @@ void finalize(const argon2_context *context, argon2_instance_t *instance); * @param position Current position * @pre all block pointers must be valid */ -void fill_segment(const argon2_instance_t *instance, - argon2_position_t position); +void xmrig_ar2_fill_segment(const argon2_instance_t *instance, argon2_position_t position); /* * Function that fills the entire memory t_cost times based on the first two @@ -221,6 +215,6 @@ void fill_segment(const argon2_instance_t *instance, * @param instance Pointer to the current instance * @return ARGON2_OK if successful, @context->state */ -int fill_memory_blocks(argon2_instance_t *instance); +int xmrig_ar2_fill_memory_blocks(argon2_instance_t *instance); #endif diff --git a/src/3rdparty/argon2/lib/encoding.c b/src/3rdparty/argon2/lib/encoding.c index af56e447..6190ae8f 100644 --- a/src/3rdparty/argon2/lib/encoding.c +++ b/src/3rdparty/argon2/lib/encoding.c @@ -323,7 +323,7 @@ int decode_string(argon2_context *ctx, const char *str, argon2_type type) { ctx->flags = ARGON2_DEFAULT_FLAGS; /* On return, must have valid context */ - validation_result = validate_inputs(ctx); + validation_result = xmrig_ar2_validate_inputs(ctx); if (validation_result != ARGON2_OK) { return validation_result; } @@ -371,7 +371,7 @@ int encode_string(char *dst, size_t dst_len, argon2_context *ctx, } while ((void)0, 0) const char* type_string = argon2_type2string(type, 0); - int validation_result = validate_inputs(ctx); + int validation_result = xmrig_ar2_validate_inputs(ctx); if (!type_string) { return ARGON2_ENCODING_FAIL; diff --git a/src/3rdparty/argon2/lib/impl-select.c b/src/3rdparty/argon2/lib/impl-select.c index 965b639e..bc7d1438 100644 --- a/src/3rdparty/argon2/lib/impl-select.c +++ b/src/3rdparty/argon2/lib/impl-select.c @@ -2,79 +2,81 @@ #include #include "impl-select.h" - #include "3rdparty/argon2.h" -#define BENCH_SAMPLES 1024 + +extern uint64_t uv_hrtime(void); + + +#define BENCH_SAMPLES 1024U #define BENCH_MEM_BLOCKS 512 -static argon2_impl selected_argon_impl = { - "default", NULL, fill_segment_default -}; + +#ifdef _MSC_VER +# define strcasecmp _stricmp +#endif + + +static argon2_impl selected_argon_impl = { "default", NULL, fill_segment_default }; + /* the benchmark routine is not thread-safe, so we can use a global var here: */ static block memory[BENCH_MEM_BLOCKS]; -static uint64_t benchmark_impl(const argon2_impl *impl) { - clock_t time; - unsigned int i; - uint64_t bench; - argon2_instance_t instance; - argon2_position_t pos; +static uint64_t benchmark_impl(const argon2_impl *impl) { memset(memory, 0, sizeof(memory)); - instance.version = ARGON2_VERSION_NUMBER; - instance.memory = memory; - instance.passes = 1; - instance.memory_blocks = BENCH_MEM_BLOCKS; + argon2_instance_t instance; + instance.version = ARGON2_VERSION_NUMBER; + instance.memory = memory; + instance.passes = 1; + instance.memory_blocks = BENCH_MEM_BLOCKS; instance.segment_length = BENCH_MEM_BLOCKS / ARGON2_SYNC_POINTS; - instance.lane_length = instance.segment_length * ARGON2_SYNC_POINTS; - instance.lanes = 1; - instance.threads = 1; - instance.type = Argon2_i; + instance.lane_length = instance.segment_length * ARGON2_SYNC_POINTS; + instance.lanes = 1; + instance.threads = 1; + instance.type = Argon2_id; - pos.lane = 0; - pos.pass = 0; - pos.slice = 0; - pos.index = 0; + argon2_position_t pos; + pos.lane = 0; + pos.pass = 0; + pos.slice = 0; + pos.index = 0; /* warm-up cache: */ impl->fill_segment(&instance, pos); /* OK, now measure: */ - bench = 0; - time = clock(); - for (i = 0; i < BENCH_SAMPLES; i++) { + const uint64_t time = uv_hrtime(); + + for (uint32_t i = 0; i < BENCH_SAMPLES; i++) { impl->fill_segment(&instance, pos); } - time = clock() - time; - bench = (uint64_t)time; - return bench; + + return uv_hrtime() - time; } + void argon2_select_impl() { argon2_impl_list impls; - unsigned int i; const argon2_impl *best_impl = NULL; uint64_t best_bench = UINT_MAX; argon2_get_impl_list(&impls); - for (i = 0; i < impls.count; i++) { + for (uint32_t i = 0; i < impls.count; i++) { const argon2_impl *impl = &impls.entries[i]; - uint64_t bench; if (impl->check != NULL && !impl->check()) { continue; } - bench = benchmark_impl(impl); - + const uint64_t bench = benchmark_impl(impl); if (bench < best_bench) { best_bench = bench; - best_impl = impl; + best_impl = impl; } } @@ -83,11 +85,13 @@ void argon2_select_impl() } } -void fill_segment(const argon2_instance_t *instance, argon2_position_t position) + +void xmrig_ar2_fill_segment(const argon2_instance_t *instance, argon2_position_t position) { selected_argon_impl.fill_segment(instance, position); } + const char *argon2_get_impl_name() { return selected_argon_impl.name; @@ -97,14 +101,12 @@ const char *argon2_get_impl_name() int argon2_select_impl_by_name(const char *name) { argon2_impl_list impls; - unsigned int i; - argon2_get_impl_list(&impls); - for (i = 0; i < impls.count; i++) { + for (uint32_t i = 0; i < impls.count; i++) { const argon2_impl *impl = &impls.entries[i]; - if (strcmp(impl->name, name) == 0) { + if (strcasecmp(impl->name, name) == 0) { selected_argon_impl = *impl; return 1; diff --git a/src/3rdparty/epee/LICENSE.txt b/src/3rdparty/epee/LICENSE.txt new file mode 100644 index 00000000..9835c2f6 --- /dev/null +++ b/src/3rdparty/epee/LICENSE.txt @@ -0,0 +1,25 @@ +Copyright (c) 2006-2013, Andrey N. Sabelnikov, www.sabelnikov.net +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Andrey N. Sabelnikov nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL Andrey N. Sabelnikov BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/3rdparty/epee/README.md b/src/3rdparty/epee/README.md new file mode 100644 index 00000000..2f06fe06 --- /dev/null +++ b/src/3rdparty/epee/README.md @@ -0,0 +1 @@ +epee - is a small library of helpers, wrappers, tools and so on, used to make my life easier. diff --git a/src/3rdparty/epee/span.h b/src/3rdparty/epee/span.h new file mode 100644 index 00000000..74bf0969 --- /dev/null +++ b/src/3rdparty/epee/span.h @@ -0,0 +1,176 @@ +// Copyright (c) 2017-2020, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#pragma once + +#include +#include +#include +#include +#include + +namespace epee +{ + /*! + \brief Non-owning sequence of data. Does not deep copy + + Inspired by `gsl::span` and/or `boost::iterator_range`. This class is + intended to be used as a parameter type for functions that need to take a + writable or read-only sequence of data. Most common cases are `span` + and `span`. Using as a class member is only recommended if + clearly documented as not doing a deep-copy. C-arrays are easily convertible + to this type. + + \note Conversion from C string literal to `span` will include + the NULL-terminator. + \note Never allows derived-to-base pointer conversion; an array of derived + types is not an array of base types. + */ + template + class span + { + template + static constexpr bool safe_conversion() noexcept + { + // Allow exact matches or `T*` -> `const T*`. + using with_const = typename std::add_const::type; + return std::is_same() || + (std::is_const() && std::is_same()); + } + + public: + using value_type = T; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using pointer = T*; + using const_pointer = const T*; + using reference = T&; + using const_reference = const T&; + using iterator = pointer; + using const_iterator = const_pointer; + + constexpr span() noexcept : ptr(nullptr), len(0) {} + constexpr span(std::nullptr_t) noexcept : span() {} + + //! Prevent derived-to-base conversions; invalid in this context. + template()>::type> + constexpr span(U* const src_ptr, const std::size_t count) noexcept + : ptr(src_ptr), len(count) {} + + //! Conversion from C-array. Prevents common bugs with sizeof + arrays. + template + constexpr span(T (&src)[N]) noexcept : span(src, N) {} + + constexpr span(const span&) noexcept = default; + span& operator=(const span&) noexcept = default; + + /*! Try to remove `amount` elements from beginning of span. + \return Number of elements removed. */ + std::size_t remove_prefix(std::size_t amount) noexcept + { + amount = std::min(len, amount); + ptr += amount; + len -= amount; + return amount; + } + + constexpr iterator begin() const noexcept { return ptr; } + constexpr const_iterator cbegin() const noexcept { return ptr; } + + constexpr iterator end() const noexcept { return begin() + size(); } + constexpr const_iterator cend() const noexcept { return cbegin() + size(); } + + constexpr bool empty() const noexcept { return size() == 0; } + constexpr pointer data() const noexcept { return ptr; } + constexpr std::size_t size() const noexcept { return len; } + constexpr std::size_t size_bytes() const noexcept { return size() * sizeof(value_type); } + + T &operator[](size_t idx) noexcept { return ptr[idx]; } + const T &operator[](size_t idx) const noexcept { return ptr[idx]; } + + private: + T* ptr; + std::size_t len; + }; + + //! \return `span` from a STL compatible `src`. + template + constexpr span to_span(const T& src) + { + // compiler provides diagnostic if size() is not size_t. + return {src.data(), src.size()}; + } + + //! \return `span` from a STL compatible `src`. + template + constexpr span to_mut_span(T& src) + { + // compiler provides diagnostic if size() is not size_t. + return {src.data(), src.size()}; + } + + template + constexpr bool has_padding() noexcept + { + return !std::is_standard_layout() || alignof(T) != 1; + } + + //! \return Cast data from `src` as `span`. + template + span to_byte_span(const span src) noexcept + { + static_assert(!has_padding(), "source type may have padding"); + return {reinterpret_cast(src.data()), src.size_bytes()}; + } + + //! \return `span` which represents the bytes at `&src`. + template + span as_byte_span(const T& src) noexcept + { + static_assert(!std::is_empty(), "empty types will not work -> sizeof == 1"); + static_assert(!has_padding(), "source type may have padding"); + return {reinterpret_cast(std::addressof(src)), sizeof(T)}; + } + + //! \return `span` which represents the bytes at `&src`. + template + span as_mut_byte_span(T& src) noexcept + { + static_assert(!std::is_empty(), "empty types will not work -> sizeof == 1"); + static_assert(!has_padding(), "source type may have padding"); + return {reinterpret_cast(std::addressof(src)), sizeof(T)}; + } + + //! make a span from a std::string + template + span strspan(const std::string &s) noexcept + { + static_assert(std::is_same() || std::is_same() || std::is_same() || std::is_same(), "Unexpected type"); + return {reinterpret_cast(s.data()), s.size()}; + } +} diff --git a/src/3rdparty/fmt/LICENSE.rst b/src/3rdparty/fmt/LICENSE.rst new file mode 100644 index 00000000..f0ec3db4 --- /dev/null +++ b/src/3rdparty/fmt/LICENSE.rst @@ -0,0 +1,27 @@ +Copyright (c) 2012 - present, Victor Zverovich + +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. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into a machine-executable object form of such +source code, you may redistribute such embedded portions in such object form +without including the above copyright and permission notices. diff --git a/src/3rdparty/fmt/README.rst b/src/3rdparty/fmt/README.rst new file mode 100644 index 00000000..12dfaf84 --- /dev/null +++ b/src/3rdparty/fmt/README.rst @@ -0,0 +1,505 @@ +{fmt} +===== + +.. image:: https://travis-ci.org/fmtlib/fmt.png?branch=master + :target: https://travis-ci.org/fmtlib/fmt + +.. image:: https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v + :target: https://ci.appveyor.com/project/vitaut/fmt + +.. image:: https://oss-fuzz-build-logs.storage.googleapis.com/badges/libfmt.svg + :alt: fmt is continuously fuzzed at oss-fuzz + :target: https://bugs.chromium.org/p/oss-fuzz/issues/list?\ + colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20\ + Summary&q=proj%3Dlibfmt&can=1 + +.. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg + :alt: Ask questions at StackOverflow with the tag fmt + :target: https://stackoverflow.com/questions/tagged/fmt + +**{fmt}** is an open-source formatting library providing a fast and safe +alternative to C stdio and C++ iostreams. + +If you like this project, please consider donating to BYSOL, +an initiative to help victims of political repressions in Belarus: +https://www.facebook.com/donate/759400044849707/108388587646909/. + +`Documentation `__ + +Q&A: ask questions on `StackOverflow with the tag fmt +`_. + +Try {fmt} in `Compiler Explorer `_. + +Features +-------- + +* Simple `format API `_ with positional arguments + for localization +* Implementation of `C++20 std::format + `__ +* `Format string syntax `_ similar to Python's + `format `_ +* Fast IEEE 754 floating-point formatter with correct rounding, shortness and + round-trip guarantees. +* Safe `printf implementation + `_ including the POSIX + extension for positional arguments +* Extensibility: `support for user-defined types + `_ +* High performance: faster than common standard library implementations of + ``(s)printf``, iostreams, ``to_string`` and ``to_chars``, see `Speed tests`_ + and `Converting a hundred million integers to strings per second + `_ +* Small code size both in terms of source code with the minimum configuration + consisting of just three files, ``core.h``, ``format.h`` and ``format-inl.h``, + and compiled code; see `Compile time and code bloat`_ +* Reliability: the library has an extensive set of `tests + `_ and is `continuously fuzzed + `_ +* Safety: the library is fully type safe, errors in format strings can be + reported at compile time, automatic memory management prevents buffer overflow + errors +* Ease of use: small self-contained code base, no external dependencies, + permissive MIT `license + `_ +* `Portability `_ with + consistent output across platforms and support for older compilers +* Clean warning-free codebase even on high warning levels such as + ``-Wall -Wextra -pedantic`` +* Locale-independence by default +* Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro + +See the `documentation `_ for more details. + +Examples +-------- + +**Print to stdout** (`run `_) + +.. code:: c++ + + #include + + int main() { + fmt::print("Hello, world!\n"); + } + +**Format a string** (`run `_) + +.. code:: c++ + + std::string s = fmt::format("The answer is {}.", 42); + // s == "The answer is 42." + +**Format a string using positional arguments** (`run `_) + +.. code:: c++ + + std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); + // s == "I'd rather be happy than right." + +**Print chrono durations** (`run `_) + +.. code:: c++ + + #include + + int main() { + using namespace std::literals::chrono_literals; + fmt::print("Default format: {} {}\n", 42s, 100ms); + fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); + } + +Output:: + + Default format: 42s 100ms + strftime-like format: 03:15:30 + +**Print a container** (`run `_) + +.. code:: c++ + + #include + #include + + int main() { + std::vector v = {1, 2, 3}; + fmt::print("{}\n", v); + } + +Output:: + + {1, 2, 3} + +**Check a format string at compile time** + +.. code:: c++ + + std::string s = fmt::format(FMT_STRING("{:d}"), "don't panic"); + +This gives a compile-time error because ``d`` is an invalid format specifier for +a string. + +**Write a file from a single thread** + +.. code:: c++ + + #include + + int main() { + auto out = fmt::output_file("guide.txt"); + out.print("Don't {}", "Panic"); + } + +This can be `5 to 9 times faster than fprintf +`_. + +**Print with colors and text styles** + +.. code:: c++ + + #include + + int main() { + fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, + "Hello, {}!\n", "world"); + fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | + fmt::emphasis::underline, "Hello, {}!\n", "мир"); + fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, + "Hello, {}!\n", "世界"); + } + +Output on a modern terminal: + +.. image:: https://user-images.githubusercontent.com/ + 576385/88485597-d312f600-cf2b-11ea-9cbe-61f535a86e28.png + +Benchmarks +---------- + +Speed tests +~~~~~~~~~~~ + +================= ============= =========== +Library Method Run Time, s +================= ============= =========== +libc printf 1.04 +libc++ std::ostream 3.05 +{fmt} 6.1.1 fmt::print 0.75 +Boost Format 1.67 boost::format 7.24 +Folly Format folly::format 2.23 +================= ============= =========== + +{fmt} is the fastest of the benchmarked methods, ~35% faster than ``printf``. + +The above results were generated by building ``tinyformat_test.cpp`` on macOS +10.14.6 with ``clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT``, and taking the +best of three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"`` +or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for +further details refer to the `source +`_. + +{fmt} is up to 10x faster than ``std::ostringstream`` and ``sprintf`` on +floating-point formatting (`dtoa-benchmark `_) +and faster than `double-conversion `_: + +.. image:: https://user-images.githubusercontent.com/576385/ + 69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png + :target: https://fmt.dev/unknown_mac64_clang10.0.html + +Compile time and code bloat +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The script `bloat-test.py +`_ +from `format-benchmark `_ +tests compile time and code bloat for nontrivial projects. +It generates 100 translation units and uses ``printf()`` or its alternative +five times in each to simulate a medium sized project. The resulting +executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42), +macOS Sierra, best of three) is shown in the following tables. + +**Optimized build (-O3)** + +============= =============== ==================== ================== +Method Compile Time, s Executable size, KiB Stripped size, KiB +============= =============== ==================== ================== +printf 2.6 29 26 +printf+string 16.4 29 26 +iostreams 31.1 59 55 +{fmt} 19.0 37 34 +Boost Format 91.9 226 203 +Folly Format 115.7 101 88 +============= =============== ==================== ================== + +As you can see, {fmt} has 60% less overhead in terms of resulting binary code +size compared to iostreams and comes pretty close to ``printf``. Boost Format +and Folly Format have the largest overheads. + +``printf+string`` is the same as ``printf`` but with extra ```` +include to measure the overhead of the latter. + +**Non-optimized build** + +============= =============== ==================== ================== +Method Compile Time, s Executable size, KiB Stripped size, KiB +============= =============== ==================== ================== +printf 2.2 33 30 +printf+string 16.0 33 30 +iostreams 28.3 56 52 +{fmt} 18.2 59 50 +Boost Format 54.1 365 303 +Folly Format 79.9 445 430 +============= =============== ==================== ================== + +``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared libraries to +compare formatting function overhead only. Boost Format is a +header-only library so it doesn't provide any linkage options. + +Running the tests +~~~~~~~~~~~~~~~~~ + +Please refer to `Building the library`__ for the instructions on how to build +the library and run the unit tests. + +__ https://fmt.dev/latest/usage.html#building-the-library + +Benchmarks reside in a separate repository, +`format-benchmarks `_, +so to run the benchmarks you first need to clone this repository and +generate Makefiles with CMake:: + + $ git clone --recursive https://github.com/fmtlib/format-benchmark.git + $ cd format-benchmark + $ cmake . + +Then you can run the speed test:: + + $ make speed-test + +or the bloat test:: + + $ make bloat-test + +Projects using this library +--------------------------- + +* `0 A.D. `_: A free, open-source, cross-platform + real-time strategy game + +* `AMPL/MP `_: + An open-source library for mathematical programming + +* `Aseprite `_: + Animated sprite editor & pixel art tool + +* `AvioBook `_: A comprehensive aircraft + operations suite + +* `Celestia `_: Real-time 3D visualization of space + +* `Ceph `_: A scalable distributed storage system + +* `ccache `_: A compiler cache + +* `ClickHouse `_: analytical database + management system + +* `CUAUV `_: Cornell University's autonomous underwater + vehicle + +* `Drake `_: A planning, control, and analysis toolbox + for nonlinear dynamical systems (MIT) + +* `Envoy `_: C++ L7 proxy and communication bus + (Lyft) + +* `FiveM `_: a modification framework for GTA V + +* `Folly `_: Facebook open-source library + +* `HarpyWar/pvpgn `_: + Player vs Player Gaming Network with tweaks + +* `KBEngine `_: An open-source MMOG server + engine + +* `Keypirinha `_: A semantic launcher for Windows + +* `Kodi `_ (formerly xbmc): Home theater software + +* `Knuth `_: High-performance Bitcoin full-node + +* `Microsoft Verona `_: + Research programming language for concurrent ownership + +* `MongoDB `_: Distributed document database + +* `MongoDB Smasher `_: A small tool to + generate randomized datasets + +* `OpenSpace `_: An open-source + astrovisualization framework + +* `PenUltima Online (POL) `_: + An MMO server, compatible with most Ultima Online clients + +* `PyTorch `_: An open-source machine + learning library + +* `quasardb `_: A distributed, high-performance, + associative database + +* `Quill `_: Asynchronous low-latency logging library + +* `QKW `_: Generalizing aliasing to simplify + navigation, and executing complex multi-line terminal command sequences + +* `readpe `_: Read Portable Executable + +* `redis-cerberus `_: A Redis cluster + proxy + +* `redpanda `_: A 10x faster Kafka® replacement + for mission critical systems written in C++ + +* `rpclib `_: A modern C++ msgpack-RPC server and client + library + +* `Salesforce Analytics Cloud + `_: + Business intelligence software + +* `Scylla `_: A Cassandra-compatible NoSQL data store + that can handle 1 million transactions per second on a single server + +* `Seastar `_: An advanced, open-source C++ + framework for high-performance server applications on modern hardware + +* `spdlog `_: Super fast C++ logging library + +* `Stellar `_: Financial platform + +* `Touch Surgery `_: Surgery simulator + +* `TrinityCore `_: Open-source + MMORPG framework + +* `Windows Terminal `_: The new Windows + Terminal + +`More... `_ + +If you are aware of other projects using this library, please let me know +by `email `_ or by submitting an +`issue `_. + +Motivation +---------- + +So why yet another formatting library? + +There are plenty of methods for doing this task, from standard ones like +the printf family of function and iostreams to Boost Format and FastFormat +libraries. The reason for creating a new library is that every existing +solution that I found either had serious issues or didn't provide +all the features I needed. + +printf +~~~~~~ + +The good thing about ``printf`` is that it is pretty fast and readily available +being a part of the C standard library. The main drawback is that it +doesn't support user-defined types. ``printf`` also has safety issues although +they are somewhat mitigated with `__attribute__ ((format (printf, ...)) +`_ in GCC. +There is a POSIX extension that adds positional arguments required for +`i18n `_ +to ``printf`` but it is not a part of C99 and may not be available on some +platforms. + +iostreams +~~~~~~~~~ + +The main issue with iostreams is best illustrated with an example: + +.. code:: c++ + + std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; + +which is a lot of typing compared to printf: + +.. code:: c++ + + printf("%.2f\n", 1.23456); + +Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams +don't support positional arguments by design. + +The good part is that iostreams support user-defined types and are safe although +error handling is awkward. + +Boost Format +~~~~~~~~~~~~ + +This is a very powerful library which supports both ``printf``-like format +strings and positional arguments. Its main drawback is performance. According to +various, benchmarks it is much slower than other methods considered here. Boost +Format also has excessive build times and severe code bloat issues (see +`Benchmarks`_). + +FastFormat +~~~~~~~~~~ + +This is an interesting library which is fast, safe and has positional arguments. +However, it has significant limitations, citing its author: + + Three features that have no hope of being accommodated within the + current design are: + + * Leading zeros (or any other non-space padding) + * Octal/hexadecimal encoding + * Runtime width/alignment specification + +It is also quite big and has a heavy dependency, STLSoft, which might be too +restrictive for using it in some projects. + +Boost Spirit.Karma +~~~~~~~~~~~~~~~~~~ + +This is not really a formatting library but I decided to include it here for +completeness. As iostreams, it suffers from the problem of mixing verbatim text +with arguments. The library is pretty fast, but slower on integer formatting +than ``fmt::format_to`` with format string compilation on Karma's own benchmark, +see `Converting a hundred million integers to strings per second +`_. + +License +------- + +{fmt} is distributed under the MIT `license +`_. + +Documentation License +--------------------- + +The `Format String Syntax `_ +section in the documentation is based on the one from Python `string module +documentation `_. +For this reason the documentation is distributed under the Python Software +Foundation license available in `doc/python-license.txt +`_. +It only applies if you distribute the documentation of {fmt}. + +Maintainers +----------- + +The {fmt} library is maintained by Victor Zverovich (`vitaut +`_) and Jonathan Müller (`foonathan +`_) with contributions from many other people. +See `Contributors `_ and +`Releases `_ for some of the names. +Let us know if your contribution is not listed or mentioned incorrectly and +we'll make it right. diff --git a/src/3rdparty/fmt/chrono.h b/src/3rdparty/fmt/chrono.h new file mode 100644 index 00000000..1a3b8d5e --- /dev/null +++ b/src/3rdparty/fmt/chrono.h @@ -0,0 +1,1118 @@ +// Formatting library for C++ - chrono support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CHRONO_H_ +#define FMT_CHRONO_H_ + +#include +#include +#include +#include + +#include "format.h" +#include "locale.h" + +FMT_BEGIN_NAMESPACE + +// Enable safe chrono durations, unless explicitly disabled. +#ifndef FMT_SAFE_DURATION_CAST +# define FMT_SAFE_DURATION_CAST 1 +#endif +#if FMT_SAFE_DURATION_CAST + +// For conversion between std::chrono::durations without undefined +// behaviour or erroneous results. +// This is a stripped down version of duration_cast, for inclusion in fmt. +// See https://github.com/pauldreik/safe_duration_cast +// +// Copyright Paul Dreik 2019 +namespace safe_duration_cast { + +template ::value && + std::numeric_limits::is_signed == + std::numeric_limits::is_signed)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + using F = std::numeric_limits; + using T = std::numeric_limits; + static_assert(F::is_integer, "From must be integral"); + static_assert(T::is_integer, "To must be integral"); + + // A and B are both signed, or both unsigned. + if (F::digits <= T::digits) { + // From fits in To without any problem. + } else { + // From does not always fit in To, resort to a dynamic check. + if (from < (T::min)() || from > (T::max)()) { + // outside range. + ec = 1; + return {}; + } + } + return static_cast(from); +} + +/** + * converts From to To, without loss. If the dynamic value of from + * can't be converted to To without loss, ec is set. + */ +template ::value && + std::numeric_limits::is_signed != + std::numeric_limits::is_signed)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + using F = std::numeric_limits; + using T = std::numeric_limits; + static_assert(F::is_integer, "From must be integral"); + static_assert(T::is_integer, "To must be integral"); + + if (detail::const_check(F::is_signed && !T::is_signed)) { + // From may be negative, not allowed! + if (fmt::detail::is_negative(from)) { + ec = 1; + return {}; + } + // From is positive. Can it always fit in To? + if (F::digits > T::digits && + from > static_cast(detail::max_value())) { + ec = 1; + return {}; + } + } + + if (!F::is_signed && T::is_signed && F::digits >= T::digits && + from > static_cast(detail::max_value())) { + ec = 1; + return {}; + } + return static_cast(from); // Lossless conversion. +} + +template ::value)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + return from; +} // function + +// clang-format off +/** + * converts From to To if possible, otherwise ec is set. + * + * input | output + * ---------------------------------|--------------- + * NaN | NaN + * Inf | Inf + * normal, fits in output | converted (possibly lossy) + * normal, does not fit in output | ec is set + * subnormal | best effort + * -Inf | -Inf + */ +// clang-format on +template ::value)> +FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) { + ec = 0; + using T = std::numeric_limits; + static_assert(std::is_floating_point::value, "From must be floating"); + static_assert(std::is_floating_point::value, "To must be floating"); + + // catch the only happy case + if (std::isfinite(from)) { + if (from >= T::lowest() && from <= (T::max)()) { + return static_cast(from); + } + // not within range. + ec = 1; + return {}; + } + + // nan and inf will be preserved + return static_cast(from); +} // function + +template ::value)> +FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) { + ec = 0; + static_assert(std::is_floating_point::value, "From must be floating"); + return from; +} + +/** + * safe duration cast between integral durations + */ +template ::value), + FMT_ENABLE_IF(std::is_integral::value)> +To safe_duration_cast(std::chrono::duration from, + int& ec) { + using From = std::chrono::duration; + ec = 0; + // the basic idea is that we need to convert from count() in the from type + // to count() in the To type, by multiplying it with this: + struct Factor + : std::ratio_divide {}; + + static_assert(Factor::num > 0, "num must be positive"); + static_assert(Factor::den > 0, "den must be positive"); + + // the conversion is like this: multiply from.count() with Factor::num + // /Factor::den and convert it to To::rep, all this without + // overflow/underflow. let's start by finding a suitable type that can hold + // both To, From and Factor::num + using IntermediateRep = + typename std::common_type::type; + + // safe conversion to IntermediateRep + IntermediateRep count = + lossless_integral_conversion(from.count(), ec); + if (ec) return {}; + // multiply with Factor::num without overflow or underflow + if (detail::const_check(Factor::num != 1)) { + const auto max1 = detail::max_value() / Factor::num; + if (count > max1) { + ec = 1; + return {}; + } + const auto min1 = + (std::numeric_limits::min)() / Factor::num; + if (count < min1) { + ec = 1; + return {}; + } + count *= Factor::num; + } + + if (detail::const_check(Factor::den != 1)) count /= Factor::den; + auto tocount = lossless_integral_conversion(count, ec); + return ec ? To() : To(tocount); +} + +/** + * safe duration_cast between floating point durations + */ +template ::value), + FMT_ENABLE_IF(std::is_floating_point::value)> +To safe_duration_cast(std::chrono::duration from, + int& ec) { + using From = std::chrono::duration; + ec = 0; + if (std::isnan(from.count())) { + // nan in, gives nan out. easy. + return To{std::numeric_limits::quiet_NaN()}; + } + // maybe we should also check if from is denormal, and decide what to do about + // it. + + // +-inf should be preserved. + if (std::isinf(from.count())) { + return To{from.count()}; + } + + // the basic idea is that we need to convert from count() in the from type + // to count() in the To type, by multiplying it with this: + struct Factor + : std::ratio_divide {}; + + static_assert(Factor::num > 0, "num must be positive"); + static_assert(Factor::den > 0, "den must be positive"); + + // the conversion is like this: multiply from.count() with Factor::num + // /Factor::den and convert it to To::rep, all this without + // overflow/underflow. let's start by finding a suitable type that can hold + // both To, From and Factor::num + using IntermediateRep = + typename std::common_type::type; + + // force conversion of From::rep -> IntermediateRep to be safe, + // even if it will never happen be narrowing in this context. + IntermediateRep count = + safe_float_conversion(from.count(), ec); + if (ec) { + return {}; + } + + // multiply with Factor::num without overflow or underflow + if (Factor::num != 1) { + constexpr auto max1 = detail::max_value() / + static_cast(Factor::num); + if (count > max1) { + ec = 1; + return {}; + } + constexpr auto min1 = std::numeric_limits::lowest() / + static_cast(Factor::num); + if (count < min1) { + ec = 1; + return {}; + } + count *= static_cast(Factor::num); + } + + // this can't go wrong, right? den>0 is checked earlier. + if (Factor::den != 1) { + using common_t = typename std::common_type::type; + count /= static_cast(Factor::den); + } + + // convert to the to type, safely + using ToRep = typename To::rep; + + const ToRep tocount = safe_float_conversion(count, ec); + if (ec) { + return {}; + } + return To{tocount}; +} +} // namespace safe_duration_cast +#endif + +// Prevents expansion of a preceding token as a function-style macro. +// Usage: f FMT_NOMACRO() +#define FMT_NOMACRO + +namespace detail { +inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); } +inline null<> localtime_s(...) { return null<>(); } +inline null<> gmtime_r(...) { return null<>(); } +inline null<> gmtime_s(...) { return null<>(); } +} // namespace detail + +// Thread-safe replacement for std::localtime +inline std::tm localtime(std::time_t time) { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + dispatcher(std::time_t t) : time_(t) {} + + bool run() { + using namespace fmt::detail; + return handle(localtime_r(&time_, &tm_)); + } + + bool handle(std::tm* tm) { return tm != nullptr; } + + bool handle(detail::null<>) { + using namespace fmt::detail; + return fallback(localtime_s(&tm_, &time_)); + } + + bool fallback(int res) { return res == 0; } + +#if !FMT_MSC_VER + bool fallback(detail::null<>) { + using namespace fmt::detail; + std::tm* tm = std::localtime(&time_); + if (tm) tm_ = *tm; + return tm != nullptr; + } +#endif + }; + dispatcher lt(time); + // Too big time values may be unsupported. + if (!lt.run()) FMT_THROW(format_error("time_t value out of range")); + return lt.tm_; +} + +inline std::tm localtime( + std::chrono::time_point time_point) { + return localtime(std::chrono::system_clock::to_time_t(time_point)); +} + +// Thread-safe replacement for std::gmtime +inline std::tm gmtime(std::time_t time) { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + dispatcher(std::time_t t) : time_(t) {} + + bool run() { + using namespace fmt::detail; + return handle(gmtime_r(&time_, &tm_)); + } + + bool handle(std::tm* tm) { return tm != nullptr; } + + bool handle(detail::null<>) { + using namespace fmt::detail; + return fallback(gmtime_s(&tm_, &time_)); + } + + bool fallback(int res) { return res == 0; } + +#if !FMT_MSC_VER + bool fallback(detail::null<>) { + std::tm* tm = std::gmtime(&time_); + if (tm) tm_ = *tm; + return tm != nullptr; + } +#endif + }; + dispatcher gt(time); + // Too big time values may be unsupported. + if (!gt.run()) FMT_THROW(format_error("time_t value out of range")); + return gt.tm_; +} + +inline std::tm gmtime( + std::chrono::time_point time_point) { + return gmtime(std::chrono::system_clock::to_time_t(time_point)); +} + +namespace detail { +inline size_t strftime(char* str, size_t count, const char* format, + const std::tm* time) { + return std::strftime(str, count, format, time); +} + +inline size_t strftime(wchar_t* str, size_t count, const wchar_t* format, + const std::tm* time) { + return std::wcsftime(str, count, format, time); +} +} // namespace detail + +template +struct formatter, Char> + : formatter { + template + auto format(std::chrono::time_point val, + FormatContext& ctx) -> decltype(ctx.out()) { + std::tm time = localtime(val); + return formatter::format(time, ctx); + } +}; + +template struct formatter { + template + auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + auto it = ctx.begin(); + if (it != ctx.end() && *it == ':') ++it; + auto end = it; + while (end != ctx.end() && *end != '}') ++end; + tm_format.reserve(detail::to_unsigned(end - it + 1)); + tm_format.append(it, end); + tm_format.push_back('\0'); + return end; + } + + template + auto format(const std::tm& tm, FormatContext& ctx) -> decltype(ctx.out()) { + basic_memory_buffer buf; + size_t start = buf.size(); + for (;;) { + size_t size = buf.capacity() - start; + size_t count = detail::strftime(&buf[start], size, &tm_format[0], &tm); + if (count != 0) { + buf.resize(start + count); + break; + } + if (size >= tm_format.size() * 256) { + // If the buffer is 256 times larger than the format string, assume + // that `strftime` gives an empty result. There doesn't seem to be a + // better way to distinguish the two cases: + // https://github.com/fmtlib/fmt/issues/367 + break; + } + const size_t MIN_GROWTH = 10; + buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH)); + } + return std::copy(buf.begin(), buf.end(), ctx.out()); + } + + basic_memory_buffer tm_format; +}; + +namespace detail { +template FMT_CONSTEXPR const char* get_units() { + return nullptr; +} +template <> FMT_CONSTEXPR const char* get_units() { return "as"; } +template <> FMT_CONSTEXPR const char* get_units() { return "fs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ps"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ns"; } +template <> FMT_CONSTEXPR const char* get_units() { return "µs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ms"; } +template <> FMT_CONSTEXPR const char* get_units() { return "cs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ds"; } +template <> FMT_CONSTEXPR const char* get_units>() { return "s"; } +template <> FMT_CONSTEXPR const char* get_units() { return "das"; } +template <> FMT_CONSTEXPR const char* get_units() { return "hs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "ks"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Ms"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Gs"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Ts"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Ps"; } +template <> FMT_CONSTEXPR const char* get_units() { return "Es"; } +template <> FMT_CONSTEXPR const char* get_units>() { + return "m"; +} +template <> FMT_CONSTEXPR const char* get_units>() { + return "h"; +} + +enum class numeric_system { + standard, + // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale. + alternative +}; + +// Parses a put_time-like format string and invokes handler actions. +template +FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin, + const Char* end, + Handler&& handler) { + auto ptr = begin; + while (ptr != end) { + auto c = *ptr; + if (c == '}') break; + if (c != '%') { + ++ptr; + continue; + } + if (begin != ptr) handler.on_text(begin, ptr); + ++ptr; // consume '%' + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case '%': + handler.on_text(ptr - 1, ptr); + break; + case 'n': { + const Char newline[] = {'\n'}; + handler.on_text(newline, newline + 1); + break; + } + case 't': { + const Char tab[] = {'\t'}; + handler.on_text(tab, tab + 1); + break; + } + // Day of the week: + case 'a': + handler.on_abbr_weekday(); + break; + case 'A': + handler.on_full_weekday(); + break; + case 'w': + handler.on_dec0_weekday(numeric_system::standard); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::standard); + break; + // Month: + case 'b': + handler.on_abbr_month(); + break; + case 'B': + handler.on_full_month(); + break; + // Hour, minute, second: + case 'H': + handler.on_24_hour(numeric_system::standard); + break; + case 'I': + handler.on_12_hour(numeric_system::standard); + break; + case 'M': + handler.on_minute(numeric_system::standard); + break; + case 'S': + handler.on_second(numeric_system::standard); + break; + // Other: + case 'c': + handler.on_datetime(numeric_system::standard); + break; + case 'x': + handler.on_loc_date(numeric_system::standard); + break; + case 'X': + handler.on_loc_time(numeric_system::standard); + break; + case 'D': + handler.on_us_date(); + break; + case 'F': + handler.on_iso_date(); + break; + case 'r': + handler.on_12_hour_time(); + break; + case 'R': + handler.on_24_hour_time(); + break; + case 'T': + handler.on_iso_time(); + break; + case 'p': + handler.on_am_pm(); + break; + case 'Q': + handler.on_duration_value(); + break; + case 'q': + handler.on_duration_unit(); + break; + case 'z': + handler.on_utc_offset(); + break; + case 'Z': + handler.on_tz_name(); + break; + // Alternative representation: + case 'E': { + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case 'c': + handler.on_datetime(numeric_system::alternative); + break; + case 'x': + handler.on_loc_date(numeric_system::alternative); + break; + case 'X': + handler.on_loc_time(numeric_system::alternative); + break; + default: + FMT_THROW(format_error("invalid format")); + } + break; + } + case 'O': + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case 'w': + handler.on_dec0_weekday(numeric_system::alternative); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::alternative); + break; + case 'H': + handler.on_24_hour(numeric_system::alternative); + break; + case 'I': + handler.on_12_hour(numeric_system::alternative); + break; + case 'M': + handler.on_minute(numeric_system::alternative); + break; + case 'S': + handler.on_second(numeric_system::alternative); + break; + default: + FMT_THROW(format_error("invalid format")); + } + break; + default: + FMT_THROW(format_error("invalid format")); + } + begin = ptr; + } + if (begin != ptr) handler.on_text(begin, ptr); + return ptr; +} + +struct chrono_format_checker { + FMT_NORETURN void report_no_date() { FMT_THROW(format_error("no date")); } + + template void on_text(const Char*, const Char*) {} + FMT_NORETURN void on_abbr_weekday() { report_no_date(); } + FMT_NORETURN void on_full_weekday() { report_no_date(); } + FMT_NORETURN void on_dec0_weekday(numeric_system) { report_no_date(); } + FMT_NORETURN void on_dec1_weekday(numeric_system) { report_no_date(); } + FMT_NORETURN void on_abbr_month() { report_no_date(); } + FMT_NORETURN void on_full_month() { report_no_date(); } + void on_24_hour(numeric_system) {} + void on_12_hour(numeric_system) {} + void on_minute(numeric_system) {} + void on_second(numeric_system) {} + FMT_NORETURN void on_datetime(numeric_system) { report_no_date(); } + FMT_NORETURN void on_loc_date(numeric_system) { report_no_date(); } + FMT_NORETURN void on_loc_time(numeric_system) { report_no_date(); } + FMT_NORETURN void on_us_date() { report_no_date(); } + FMT_NORETURN void on_iso_date() { report_no_date(); } + void on_12_hour_time() {} + void on_24_hour_time() {} + void on_iso_time() {} + void on_am_pm() {} + void on_duration_value() {} + void on_duration_unit() {} + FMT_NORETURN void on_utc_offset() { report_no_date(); } + FMT_NORETURN void on_tz_name() { report_no_date(); } +}; + +template ::value)> +inline bool isnan(T) { + return false; +} +template ::value)> +inline bool isnan(T value) { + return std::isnan(value); +} + +template ::value)> +inline bool isfinite(T) { + return true; +} +template ::value)> +inline bool isfinite(T value) { + return std::isfinite(value); +} + +// Converts value to int and checks that it's in the range [0, upper). +template ::value)> +inline int to_nonnegative_int(T value, int upper) { + FMT_ASSERT(value >= 0 && value <= upper, "invalid value"); + (void)upper; + return static_cast(value); +} +template ::value)> +inline int to_nonnegative_int(T value, int upper) { + FMT_ASSERT( + std::isnan(value) || (value >= 0 && value <= static_cast(upper)), + "invalid value"); + (void)upper; + return static_cast(value); +} + +template ::value)> +inline T mod(T x, int y) { + return x % static_cast(y); +} +template ::value)> +inline T mod(T x, int y) { + return std::fmod(x, static_cast(y)); +} + +// If T is an integral type, maps T to its unsigned counterpart, otherwise +// leaves it unchanged (unlike std::make_unsigned). +template ::value> +struct make_unsigned_or_unchanged { + using type = T; +}; + +template struct make_unsigned_or_unchanged { + using type = typename std::make_unsigned::type; +}; + +#if FMT_SAFE_DURATION_CAST +// throwing version of safe_duration_cast +template +To fmt_safe_duration_cast(std::chrono::duration from) { + int ec; + To to = safe_duration_cast::safe_duration_cast(from, ec); + if (ec) FMT_THROW(format_error("cannot format duration")); + return to; +} +#endif + +template ::value)> +inline std::chrono::duration get_milliseconds( + std::chrono::duration d) { + // this may overflow and/or the result may not fit in the + // target type. +#if FMT_SAFE_DURATION_CAST + using CommonSecondsType = + typename std::common_type::type; + const auto d_as_common = fmt_safe_duration_cast(d); + const auto d_as_whole_seconds = + fmt_safe_duration_cast(d_as_common); + // this conversion should be nonproblematic + const auto diff = d_as_common - d_as_whole_seconds; + const auto ms = + fmt_safe_duration_cast>(diff); + return ms; +#else + auto s = std::chrono::duration_cast(d); + return std::chrono::duration_cast(d - s); +#endif +} + +template ::value)> +inline std::chrono::duration get_milliseconds( + std::chrono::duration d) { + using common_type = typename std::common_type::type; + auto ms = mod(d.count() * static_cast(Period::num) / + static_cast(Period::den) * 1000, + 1000); + return std::chrono::duration(static_cast(ms)); +} + +template +OutputIt format_duration_value(OutputIt out, Rep val, int precision) { + const Char pr_f[] = {'{', ':', '.', '{', '}', 'f', '}', 0}; + if (precision >= 0) return format_to(out, pr_f, val, precision); + const Char fp_f[] = {'{', ':', 'g', '}', 0}; + const Char format[] = {'{', '}', 0}; + return format_to(out, std::is_floating_point::value ? fp_f : format, + val); +} +template +OutputIt copy_unit(string_view unit, OutputIt out, Char) { + return std::copy(unit.begin(), unit.end(), out); +} + +template +OutputIt copy_unit(string_view unit, OutputIt out, wchar_t) { + // This works when wchar_t is UTF-32 because units only contain characters + // that have the same representation in UTF-16 and UTF-32. + utf8_to_utf16 u(unit); + return std::copy(u.c_str(), u.c_str() + u.size(), out); +} + +template +OutputIt format_duration_unit(OutputIt out) { + if (const char* unit = get_units()) + return copy_unit(string_view(unit), out, Char()); + const Char num_f[] = {'[', '{', '}', ']', 's', 0}; + if (const_check(Period::den == 1)) return format_to(out, num_f, Period::num); + const Char num_def_f[] = {'[', '{', '}', '/', '{', '}', ']', 's', 0}; + return format_to(out, num_def_f, Period::num, Period::den); +} + +template +struct chrono_formatter { + FormatContext& context; + OutputIt out; + int precision; + // rep is unsigned to avoid overflow. + using rep = + conditional_t::value && sizeof(Rep) < sizeof(int), + unsigned, typename make_unsigned_or_unchanged::type>; + rep val; + using seconds = std::chrono::duration; + seconds s; + using milliseconds = std::chrono::duration; + bool negative; + + using char_type = typename FormatContext::char_type; + + explicit chrono_formatter(FormatContext& ctx, OutputIt o, + std::chrono::duration d) + : context(ctx), + out(o), + val(static_cast(d.count())), + negative(false) { + if (d.count() < 0) { + val = 0 - val; + negative = true; + } + + // this may overflow and/or the result may not fit in the + // target type. +#if FMT_SAFE_DURATION_CAST + // might need checked conversion (rep!=Rep) + auto tmpval = std::chrono::duration(val); + s = fmt_safe_duration_cast(tmpval); +#else + s = std::chrono::duration_cast( + std::chrono::duration(val)); +#endif + } + + // returns true if nan or inf, writes to out. + bool handle_nan_inf() { + if (isfinite(val)) { + return false; + } + if (isnan(val)) { + write_nan(); + return true; + } + // must be +-inf + if (val > 0) { + write_pinf(); + } else { + write_ninf(); + } + return true; + } + + Rep hour() const { return static_cast(mod((s.count() / 3600), 24)); } + + Rep hour12() const { + Rep hour = static_cast(mod((s.count() / 3600), 12)); + return hour <= 0 ? 12 : hour; + } + + Rep minute() const { return static_cast(mod((s.count() / 60), 60)); } + Rep second() const { return static_cast(mod(s.count(), 60)); } + + std::tm time() const { + auto time = std::tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + time.tm_min = to_nonnegative_int(minute(), 60); + time.tm_sec = to_nonnegative_int(second(), 60); + return time; + } + + void write_sign() { + if (negative) { + *out++ = '-'; + negative = false; + } + } + + void write(Rep value, int width) { + write_sign(); + if (isnan(value)) return write_nan(); + uint32_or_64_or_128_t n = + to_unsigned(to_nonnegative_int(value, max_value())); + int num_digits = detail::count_digits(n); + if (width > num_digits) out = std::fill_n(out, width - num_digits, '0'); + out = format_decimal(out, n, num_digits).end; + } + + void write_nan() { std::copy_n("nan", 3, out); } + void write_pinf() { std::copy_n("inf", 3, out); } + void write_ninf() { std::copy_n("-inf", 4, out); } + + void format_localized(const tm& time, char format, char modifier = 0) { + if (isnan(val)) return write_nan(); + auto locale = context.locale().template get(); + auto& facet = std::use_facet>(locale); + std::basic_ostringstream os; + os.imbue(locale); + facet.put(os, os, ' ', &time, format, modifier); + auto str = os.str(); + std::copy(str.begin(), str.end(), out); + } + + void on_text(const char_type* begin, const char_type* end) { + std::copy(begin, end, out); + } + + // These are not implemented because durations don't have date information. + void on_abbr_weekday() {} + void on_full_weekday() {} + void on_dec0_weekday(numeric_system) {} + void on_dec1_weekday(numeric_system) {} + void on_abbr_month() {} + void on_full_month() {} + void on_datetime(numeric_system) {} + void on_loc_date(numeric_system) {} + void on_loc_time(numeric_system) {} + void on_us_date() {} + void on_iso_date() {} + void on_utc_offset() {} + void on_tz_name() {} + + void on_24_hour(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour(), 2); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + format_localized(time, 'H', 'O'); + } + + void on_12_hour(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour12(), 2); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour12(), 12); + format_localized(time, 'I', 'O'); + } + + void on_minute(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(minute(), 2); + auto time = tm(); + time.tm_min = to_nonnegative_int(minute(), 60); + format_localized(time, 'M', 'O'); + } + + void on_second(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) { + write(second(), 2); +#if FMT_SAFE_DURATION_CAST + // convert rep->Rep + using duration_rep = std::chrono::duration; + using duration_Rep = std::chrono::duration; + auto tmpval = fmt_safe_duration_cast(duration_rep{val}); +#else + auto tmpval = std::chrono::duration(val); +#endif + auto ms = get_milliseconds(tmpval); + if (ms != std::chrono::milliseconds(0)) { + *out++ = '.'; + write(ms.count(), 3); + } + return; + } + auto time = tm(); + time.tm_sec = to_nonnegative_int(second(), 60); + format_localized(time, 'S', 'O'); + } + + void on_12_hour_time() { + if (handle_nan_inf()) return; + format_localized(time(), 'r'); + } + + void on_24_hour_time() { + if (handle_nan_inf()) { + *out++ = ':'; + handle_nan_inf(); + return; + } + + write(hour(), 2); + *out++ = ':'; + write(minute(), 2); + } + + void on_iso_time() { + on_24_hour_time(); + *out++ = ':'; + if (handle_nan_inf()) return; + write(second(), 2); + } + + void on_am_pm() { + if (handle_nan_inf()) return; + format_localized(time(), 'p'); + } + + void on_duration_value() { + if (handle_nan_inf()) return; + write_sign(); + out = format_duration_value(out, val, precision); + } + + void on_duration_unit() { + out = format_duration_unit(out); + } +}; +} // namespace detail + +template +struct formatter, Char> { + private: + basic_format_specs specs; + int precision; + using arg_ref_type = detail::arg_ref; + arg_ref_type width_ref; + arg_ref_type precision_ref; + mutable basic_string_view format_str; + using duration = std::chrono::duration; + + struct spec_handler { + formatter& f; + basic_format_parse_context& context; + basic_string_view format_str; + + template FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) { + context.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view arg_id) { + context.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(detail::auto_id) { + return arg_ref_type(context.next_arg_id()); + } + + void on_error(const char* msg) { FMT_THROW(format_error(msg)); } + void on_fill(basic_string_view fill) { f.specs.fill = fill; } + void on_align(align_t align) { f.specs.align = align; } + void on_width(int width) { f.specs.width = width; } + void on_precision(int _precision) { f.precision = _precision; } + void end_precision() {} + + template void on_dynamic_width(Id arg_id) { + f.width_ref = make_arg_ref(arg_id); + } + + template void on_dynamic_precision(Id arg_id) { + f.precision_ref = make_arg_ref(arg_id); + } + }; + + using iterator = typename basic_format_parse_context::iterator; + struct parse_range { + iterator begin; + iterator end; + }; + + FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context& ctx) { + auto begin = ctx.begin(), end = ctx.end(); + if (begin == end || *begin == '}') return {begin, begin}; + spec_handler handler{*this, ctx, format_str}; + begin = detail::parse_align(begin, end, handler); + if (begin == end) return {begin, begin}; + begin = detail::parse_width(begin, end, handler); + if (begin == end) return {begin, begin}; + if (*begin == '.') { + if (std::is_floating_point::value) + begin = detail::parse_precision(begin, end, handler); + else + handler.on_error("precision not allowed for this argument type"); + } + end = parse_chrono_format(begin, end, detail::chrono_format_checker()); + return {begin, end}; + } + + public: + formatter() : precision(-1) {} + + FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) + -> decltype(ctx.begin()) { + auto range = do_parse(ctx); + format_str = basic_string_view( + &*range.begin, detail::to_unsigned(range.end - range.begin)); + return range.end; + } + + template + auto format(const duration& d, FormatContext& ctx) -> decltype(ctx.out()) { + auto begin = format_str.begin(), end = format_str.end(); + // As a possible future optimization, we could avoid extra copying if width + // is not specified. + basic_memory_buffer buf; + auto out = std::back_inserter(buf); + detail::handle_dynamic_spec(specs.width, width_ref, + ctx); + detail::handle_dynamic_spec(precision, + precision_ref, ctx); + if (begin == end || *begin == '}') { + out = detail::format_duration_value(out, d.count(), precision); + detail::format_duration_unit(out); + } else { + detail::chrono_formatter f( + ctx, out, d); + f.precision = precision; + parse_chrono_format(begin, end, f); + } + return detail::write( + ctx.out(), basic_string_view(buf.data(), buf.size()), specs); + } +}; + +FMT_END_NAMESPACE + +#endif // FMT_CHRONO_H_ diff --git a/src/3rdparty/fmt/color.h b/src/3rdparty/fmt/color.h new file mode 100644 index 00000000..a2e917df --- /dev/null +++ b/src/3rdparty/fmt/color.h @@ -0,0 +1,602 @@ +// Formatting library for C++ - color support +// +// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COLOR_H_ +#define FMT_COLOR_H_ + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +enum class color : uint32_t { + alice_blue = 0xF0F8FF, // rgb(240,248,255) + antique_white = 0xFAEBD7, // rgb(250,235,215) + aqua = 0x00FFFF, // rgb(0,255,255) + aquamarine = 0x7FFFD4, // rgb(127,255,212) + azure = 0xF0FFFF, // rgb(240,255,255) + beige = 0xF5F5DC, // rgb(245,245,220) + bisque = 0xFFE4C4, // rgb(255,228,196) + black = 0x000000, // rgb(0,0,0) + blanched_almond = 0xFFEBCD, // rgb(255,235,205) + blue = 0x0000FF, // rgb(0,0,255) + blue_violet = 0x8A2BE2, // rgb(138,43,226) + brown = 0xA52A2A, // rgb(165,42,42) + burly_wood = 0xDEB887, // rgb(222,184,135) + cadet_blue = 0x5F9EA0, // rgb(95,158,160) + chartreuse = 0x7FFF00, // rgb(127,255,0) + chocolate = 0xD2691E, // rgb(210,105,30) + coral = 0xFF7F50, // rgb(255,127,80) + cornflower_blue = 0x6495ED, // rgb(100,149,237) + cornsilk = 0xFFF8DC, // rgb(255,248,220) + crimson = 0xDC143C, // rgb(220,20,60) + cyan = 0x00FFFF, // rgb(0,255,255) + dark_blue = 0x00008B, // rgb(0,0,139) + dark_cyan = 0x008B8B, // rgb(0,139,139) + dark_golden_rod = 0xB8860B, // rgb(184,134,11) + dark_gray = 0xA9A9A9, // rgb(169,169,169) + dark_green = 0x006400, // rgb(0,100,0) + dark_khaki = 0xBDB76B, // rgb(189,183,107) + dark_magenta = 0x8B008B, // rgb(139,0,139) + dark_olive_green = 0x556B2F, // rgb(85,107,47) + dark_orange = 0xFF8C00, // rgb(255,140,0) + dark_orchid = 0x9932CC, // rgb(153,50,204) + dark_red = 0x8B0000, // rgb(139,0,0) + dark_salmon = 0xE9967A, // rgb(233,150,122) + dark_sea_green = 0x8FBC8F, // rgb(143,188,143) + dark_slate_blue = 0x483D8B, // rgb(72,61,139) + dark_slate_gray = 0x2F4F4F, // rgb(47,79,79) + dark_turquoise = 0x00CED1, // rgb(0,206,209) + dark_violet = 0x9400D3, // rgb(148,0,211) + deep_pink = 0xFF1493, // rgb(255,20,147) + deep_sky_blue = 0x00BFFF, // rgb(0,191,255) + dim_gray = 0x696969, // rgb(105,105,105) + dodger_blue = 0x1E90FF, // rgb(30,144,255) + fire_brick = 0xB22222, // rgb(178,34,34) + floral_white = 0xFFFAF0, // rgb(255,250,240) + forest_green = 0x228B22, // rgb(34,139,34) + fuchsia = 0xFF00FF, // rgb(255,0,255) + gainsboro = 0xDCDCDC, // rgb(220,220,220) + ghost_white = 0xF8F8FF, // rgb(248,248,255) + gold = 0xFFD700, // rgb(255,215,0) + golden_rod = 0xDAA520, // rgb(218,165,32) + gray = 0x808080, // rgb(128,128,128) + green = 0x008000, // rgb(0,128,0) + green_yellow = 0xADFF2F, // rgb(173,255,47) + honey_dew = 0xF0FFF0, // rgb(240,255,240) + hot_pink = 0xFF69B4, // rgb(255,105,180) + indian_red = 0xCD5C5C, // rgb(205,92,92) + indigo = 0x4B0082, // rgb(75,0,130) + ivory = 0xFFFFF0, // rgb(255,255,240) + khaki = 0xF0E68C, // rgb(240,230,140) + lavender = 0xE6E6FA, // rgb(230,230,250) + lavender_blush = 0xFFF0F5, // rgb(255,240,245) + lawn_green = 0x7CFC00, // rgb(124,252,0) + lemon_chiffon = 0xFFFACD, // rgb(255,250,205) + light_blue = 0xADD8E6, // rgb(173,216,230) + light_coral = 0xF08080, // rgb(240,128,128) + light_cyan = 0xE0FFFF, // rgb(224,255,255) + light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210) + light_gray = 0xD3D3D3, // rgb(211,211,211) + light_green = 0x90EE90, // rgb(144,238,144) + light_pink = 0xFFB6C1, // rgb(255,182,193) + light_salmon = 0xFFA07A, // rgb(255,160,122) + light_sea_green = 0x20B2AA, // rgb(32,178,170) + light_sky_blue = 0x87CEFA, // rgb(135,206,250) + light_slate_gray = 0x778899, // rgb(119,136,153) + light_steel_blue = 0xB0C4DE, // rgb(176,196,222) + light_yellow = 0xFFFFE0, // rgb(255,255,224) + lime = 0x00FF00, // rgb(0,255,0) + lime_green = 0x32CD32, // rgb(50,205,50) + linen = 0xFAF0E6, // rgb(250,240,230) + magenta = 0xFF00FF, // rgb(255,0,255) + maroon = 0x800000, // rgb(128,0,0) + medium_aquamarine = 0x66CDAA, // rgb(102,205,170) + medium_blue = 0x0000CD, // rgb(0,0,205) + medium_orchid = 0xBA55D3, // rgb(186,85,211) + medium_purple = 0x9370DB, // rgb(147,112,219) + medium_sea_green = 0x3CB371, // rgb(60,179,113) + medium_slate_blue = 0x7B68EE, // rgb(123,104,238) + medium_spring_green = 0x00FA9A, // rgb(0,250,154) + medium_turquoise = 0x48D1CC, // rgb(72,209,204) + medium_violet_red = 0xC71585, // rgb(199,21,133) + midnight_blue = 0x191970, // rgb(25,25,112) + mint_cream = 0xF5FFFA, // rgb(245,255,250) + misty_rose = 0xFFE4E1, // rgb(255,228,225) + moccasin = 0xFFE4B5, // rgb(255,228,181) + navajo_white = 0xFFDEAD, // rgb(255,222,173) + navy = 0x000080, // rgb(0,0,128) + old_lace = 0xFDF5E6, // rgb(253,245,230) + olive = 0x808000, // rgb(128,128,0) + olive_drab = 0x6B8E23, // rgb(107,142,35) + orange = 0xFFA500, // rgb(255,165,0) + orange_red = 0xFF4500, // rgb(255,69,0) + orchid = 0xDA70D6, // rgb(218,112,214) + pale_golden_rod = 0xEEE8AA, // rgb(238,232,170) + pale_green = 0x98FB98, // rgb(152,251,152) + pale_turquoise = 0xAFEEEE, // rgb(175,238,238) + pale_violet_red = 0xDB7093, // rgb(219,112,147) + papaya_whip = 0xFFEFD5, // rgb(255,239,213) + peach_puff = 0xFFDAB9, // rgb(255,218,185) + peru = 0xCD853F, // rgb(205,133,63) + pink = 0xFFC0CB, // rgb(255,192,203) + plum = 0xDDA0DD, // rgb(221,160,221) + powder_blue = 0xB0E0E6, // rgb(176,224,230) + purple = 0x800080, // rgb(128,0,128) + rebecca_purple = 0x663399, // rgb(102,51,153) + red = 0xFF0000, // rgb(255,0,0) + rosy_brown = 0xBC8F8F, // rgb(188,143,143) + royal_blue = 0x4169E1, // rgb(65,105,225) + saddle_brown = 0x8B4513, // rgb(139,69,19) + salmon = 0xFA8072, // rgb(250,128,114) + sandy_brown = 0xF4A460, // rgb(244,164,96) + sea_green = 0x2E8B57, // rgb(46,139,87) + sea_shell = 0xFFF5EE, // rgb(255,245,238) + sienna = 0xA0522D, // rgb(160,82,45) + silver = 0xC0C0C0, // rgb(192,192,192) + sky_blue = 0x87CEEB, // rgb(135,206,235) + slate_blue = 0x6A5ACD, // rgb(106,90,205) + slate_gray = 0x708090, // rgb(112,128,144) + snow = 0xFFFAFA, // rgb(255,250,250) + spring_green = 0x00FF7F, // rgb(0,255,127) + steel_blue = 0x4682B4, // rgb(70,130,180) + tan = 0xD2B48C, // rgb(210,180,140) + teal = 0x008080, // rgb(0,128,128) + thistle = 0xD8BFD8, // rgb(216,191,216) + tomato = 0xFF6347, // rgb(255,99,71) + turquoise = 0x40E0D0, // rgb(64,224,208) + violet = 0xEE82EE, // rgb(238,130,238) + wheat = 0xF5DEB3, // rgb(245,222,179) + white = 0xFFFFFF, // rgb(255,255,255) + white_smoke = 0xF5F5F5, // rgb(245,245,245) + yellow = 0xFFFF00, // rgb(255,255,0) + yellow_green = 0x9ACD32 // rgb(154,205,50) +}; // enum class color + +enum class terminal_color : uint8_t { + black = 30, + red, + green, + yellow, + blue, + magenta, + cyan, + white, + bright_black = 90, + bright_red, + bright_green, + bright_yellow, + bright_blue, + bright_magenta, + bright_cyan, + bright_white +}; + +enum class emphasis : uint8_t { + bold = 1, + italic = 1 << 1, + underline = 1 << 2, + strikethrough = 1 << 3 +}; + +// rgb is a struct for red, green and blue colors. +// Using the name "rgb" makes some editors show the color in a tooltip. +struct rgb { + FMT_CONSTEXPR rgb() : r(0), g(0), b(0) {} + FMT_CONSTEXPR rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {} + FMT_CONSTEXPR rgb(uint32_t hex) + : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {} + FMT_CONSTEXPR rgb(color hex) + : r((uint32_t(hex) >> 16) & 0xFF), + g((uint32_t(hex) >> 8) & 0xFF), + b(uint32_t(hex) & 0xFF) {} + uint8_t r; + uint8_t g; + uint8_t b; +}; + +namespace detail { + +// color is a struct of either a rgb color or a terminal color. +struct color_type { + FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {} + FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true), + value{} { + value.rgb_color = static_cast(rgb_color); + } + FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} { + value.rgb_color = (static_cast(rgb_color.r) << 16) | + (static_cast(rgb_color.g) << 8) | rgb_color.b; + } + FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(), + value{} { + value.term_color = static_cast(term_color); + } + bool is_rgb; + union color_union { + uint8_t term_color; + uint32_t rgb_color; + } value; +}; +} // namespace detail + +// Experimental text formatting support. +class text_style { + public: + FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT + : set_foreground_color(), + set_background_color(), + ems(em) {} + + FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + FMT_THROW(format_error("can't OR a terminal color")); + foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + FMT_THROW(format_error("can't OR a terminal color")); + background_color.value.rgb_color |= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) | + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR text_style operator|(text_style lhs, + const text_style& rhs) { + return lhs |= rhs; + } + + FMT_CONSTEXPR text_style& operator&=(const text_style& rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + FMT_THROW(format_error("can't AND a terminal color")); + foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + FMT_THROW(format_error("can't AND a terminal color")); + background_color.value.rgb_color &= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) & + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR text_style operator&(text_style lhs, + const text_style& rhs) { + return lhs &= rhs; + } + + FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT { + return set_foreground_color; + } + FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT { + return set_background_color; + } + FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT { + return static_cast(ems) != 0; + } + FMT_CONSTEXPR detail::color_type get_foreground() const FMT_NOEXCEPT { + FMT_ASSERT(has_foreground(), "no foreground specified for this style"); + return foreground_color; + } + FMT_CONSTEXPR detail::color_type get_background() const FMT_NOEXCEPT { + FMT_ASSERT(has_background(), "no background specified for this style"); + return background_color; + } + FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT { + FMT_ASSERT(has_emphasis(), "no emphasis specified for this style"); + return ems; + } + + private: + FMT_CONSTEXPR text_style(bool is_foreground, + detail::color_type text_color) FMT_NOEXCEPT + : set_foreground_color(), + set_background_color(), + ems() { + if (is_foreground) { + foreground_color = text_color; + set_foreground_color = true; + } else { + background_color = text_color; + set_background_color = true; + } + } + + friend FMT_CONSTEXPR_DECL text_style fg(detail::color_type foreground) + FMT_NOEXCEPT; + friend FMT_CONSTEXPR_DECL text_style bg(detail::color_type background) + FMT_NOEXCEPT; + + detail::color_type foreground_color; + detail::color_type background_color; + bool set_foreground_color; + bool set_background_color; + emphasis ems; +}; + +FMT_CONSTEXPR text_style fg(detail::color_type foreground) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/true, foreground); +} + +FMT_CONSTEXPR text_style bg(detail::color_type background) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/false, background); +} + +FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT { + return text_style(lhs) | rhs; +} + +namespace detail { + +template struct ansi_color_escape { + FMT_CONSTEXPR ansi_color_escape(detail::color_type text_color, + const char* esc) FMT_NOEXCEPT { + // If we have a terminal color, we need to output another escape code + // sequence. + if (!text_color.is_rgb) { + bool is_background = esc == detail::data::background_color; + uint32_t value = text_color.value.term_color; + // Background ASCII codes are the same as the foreground ones but with + // 10 more. + if (is_background) value += 10u; + + size_t index = 0; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + + if (value >= 100u) { + buffer[index++] = static_cast('1'); + value %= 100u; + } + buffer[index++] = static_cast('0' + value / 10u); + buffer[index++] = static_cast('0' + value % 10u); + + buffer[index++] = static_cast('m'); + buffer[index++] = static_cast('\0'); + return; + } + + for (int i = 0; i < 7; i++) { + buffer[i] = static_cast(esc[i]); + } + rgb color(text_color.value.rgb_color); + to_esc(color.r, buffer + 7, ';'); + to_esc(color.g, buffer + 11, ';'); + to_esc(color.b, buffer + 15, 'm'); + buffer[19] = static_cast(0); + } + FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT { + uint8_t em_codes[4] = {}; + uint8_t em_bits = static_cast(em); + if (em_bits & static_cast(emphasis::bold)) em_codes[0] = 1; + if (em_bits & static_cast(emphasis::italic)) em_codes[1] = 3; + if (em_bits & static_cast(emphasis::underline)) em_codes[2] = 4; + if (em_bits & static_cast(emphasis::strikethrough)) + em_codes[3] = 9; + + size_t index = 0; + for (int i = 0; i < 4; ++i) { + if (!em_codes[i]) continue; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + buffer[index++] = static_cast('0' + em_codes[i]); + buffer[index++] = static_cast('m'); + } + buffer[index++] = static_cast(0); + } + FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; } + + FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; } + FMT_CONSTEXPR const Char* end() const FMT_NOEXCEPT { + return buffer + std::char_traits::length(buffer); + } + + private: + Char buffer[7u + 3u * 4u + 1u]; + + static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out, + char delimiter) FMT_NOEXCEPT { + out[0] = static_cast('0' + c / 100); + out[1] = static_cast('0' + c / 10 % 10); + out[2] = static_cast('0' + c % 10); + out[3] = static_cast(delimiter); + } +}; + +template +FMT_CONSTEXPR ansi_color_escape make_foreground_color( + detail::color_type foreground) FMT_NOEXCEPT { + return ansi_color_escape(foreground, detail::data::foreground_color); +} + +template +FMT_CONSTEXPR ansi_color_escape make_background_color( + detail::color_type background) FMT_NOEXCEPT { + return ansi_color_escape(background, detail::data::background_color); +} + +template +FMT_CONSTEXPR ansi_color_escape make_emphasis(emphasis em) FMT_NOEXCEPT { + return ansi_color_escape(em); +} + +template +inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT { + std::fputs(chars, stream); +} + +template <> +inline void fputs(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT { + std::fputws(chars, stream); +} + +template inline void reset_color(FILE* stream) FMT_NOEXCEPT { + fputs(detail::data::reset_color, stream); +} + +template <> inline void reset_color(FILE* stream) FMT_NOEXCEPT { + fputs(detail::data::wreset_color, stream); +} + +template +inline void reset_color(buffer& buffer) FMT_NOEXCEPT { + const char* begin = data::reset_color; + const char* end = begin + sizeof(data::reset_color) - 1; + buffer.append(begin, end); +} + +template +void vformat_to(buffer& buf, const text_style& ts, + basic_string_view format_str, + basic_format_args>> args) { + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + auto emphasis = detail::make_emphasis(ts.get_emphasis()); + buf.append(emphasis.begin(), emphasis.end()); + } + if (ts.has_foreground()) { + has_style = true; + auto foreground = detail::make_foreground_color(ts.get_foreground()); + buf.append(foreground.begin(), foreground.end()); + } + if (ts.has_background()) { + has_style = true; + auto background = detail::make_background_color(ts.get_background()); + buf.append(background.begin(), background.end()); + } + detail::vformat_to(buf, format_str, args); + if (has_style) detail::reset_color(buf); +} +} // namespace detail + +template > +void vprint(std::FILE* f, const text_style& ts, const S& format, + basic_format_args>> args) { + basic_memory_buffer buf; + detail::vformat_to(buf, ts, to_string_view(format), args); + buf.push_back(Char(0)); + detail::fputs(buf.data(), f); +} + +/** + \rst + Formats a string and prints it to the specified file stream using ANSI + escape sequences to specify text formatting. + + **Example**:: + + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + \endrst + */ +template ::value)> +void print(std::FILE* f, const text_style& ts, const S& format_str, + const Args&... args) { + vprint(f, ts, format_str, + fmt::make_args_checked(format_str, args...)); +} + +/** + Formats a string and prints it to stdout using ANSI escape sequences to + specify text formatting. + Example: + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + */ +template ::value)> +void print(const text_style& ts, const S& format_str, const Args&... args) { + return print(stdout, ts, format_str, args...); +} + +template > +inline std::basic_string vformat( + const text_style& ts, const S& format_str, + basic_format_args>> args) { + basic_memory_buffer buf; + detail::vformat_to(buf, ts, to_string_view(format_str), args); + return fmt::to_string(buf); +} + +/** + \rst + Formats arguments and returns the result as a string using ANSI + escape sequences to specify text formatting. + + **Example**:: + + #include + std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), + "The answer is {}", 42); + \endrst +*/ +template > +inline std::basic_string format(const text_style& ts, const S& format_str, + const Args&... args) { + return vformat(ts, to_string_view(format_str), + fmt::make_args_checked(format_str, args...)); +} + +/** + Formats a string with the given text_style and writes the output to ``out``. + */ +template ::value)> +OutputIt vformat_to( + OutputIt out, const text_style& ts, basic_string_view format_str, + basic_format_args>> args) { + decltype(detail::get_buffer(out)) buf(detail::get_buffer_init(out)); + detail::vformat_to(buf, ts, format_str, args); + return detail::get_iterator(buf); +} + +/** + \rst + Formats arguments with the given text_style, writes the result to the output + iterator ``out`` and returns the iterator past the end of the output range. + + **Example**:: + + std::vector out; + fmt::format_to(std::back_inserter(out), + fmt::emphasis::bold | fg(fmt::color::red), "{}", 42); + \endrst +*/ +template ::value&& + detail::is_string::value)> +inline OutputIt format_to(OutputIt out, const text_style& ts, + const S& format_str, Args&&... args) { + return vformat_to(out, ts, to_string_view(format_str), + fmt::make_args_checked(format_str, args...)); +} + +FMT_END_NAMESPACE + +#endif // FMT_COLOR_H_ diff --git a/src/3rdparty/fmt/compile.h b/src/3rdparty/fmt/compile.h new file mode 100644 index 00000000..13406ce2 --- /dev/null +++ b/src/3rdparty/fmt/compile.h @@ -0,0 +1,699 @@ +// Formatting library for C++ - experimental format string compilation +// +// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COMPILE_H_ +#define FMT_COMPILE_H_ + +#include + +#include "format.h" + +FMT_BEGIN_NAMESPACE +namespace detail { + +// A compile-time string which is compiled into fast formatting code. +class compiled_string {}; + +template +struct is_compiled_string : std::is_base_of {}; + +/** + \rst + Converts a string literal *s* into a format string that will be parsed at + compile time and converted into efficient formatting code. Requires C++17 + ``constexpr if`` compiler support. + + **Example**:: + + // Converts 42 into std::string using the most efficient method and no + // runtime format string processing. + std::string s = fmt::format(FMT_COMPILE("{}"), 42); + \endrst + */ +#define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::detail::compiled_string) + +template +const T& first(const T& value, const Tail&...) { + return value; +} + +// Part of a compiled format string. It can be either literal text or a +// replacement field. +template struct format_part { + enum class kind { arg_index, arg_name, text, replacement }; + + struct replacement { + arg_ref arg_id; + dynamic_format_specs specs; + }; + + kind part_kind; + union value { + int arg_index; + basic_string_view str; + replacement repl; + + FMT_CONSTEXPR value(int index = 0) : arg_index(index) {} + FMT_CONSTEXPR value(basic_string_view s) : str(s) {} + FMT_CONSTEXPR value(replacement r) : repl(r) {} + } val; + // Position past the end of the argument id. + const Char* arg_id_end = nullptr; + + FMT_CONSTEXPR format_part(kind k = kind::arg_index, value v = {}) + : part_kind(k), val(v) {} + + static FMT_CONSTEXPR format_part make_arg_index(int index) { + return format_part(kind::arg_index, index); + } + static FMT_CONSTEXPR format_part make_arg_name(basic_string_view name) { + return format_part(kind::arg_name, name); + } + static FMT_CONSTEXPR format_part make_text(basic_string_view text) { + return format_part(kind::text, text); + } + static FMT_CONSTEXPR format_part make_replacement(replacement repl) { + return format_part(kind::replacement, repl); + } +}; + +template struct part_counter { + unsigned num_parts = 0; + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + if (begin != end) ++num_parts; + } + + FMT_CONSTEXPR int on_arg_id() { return ++num_parts, 0; } + FMT_CONSTEXPR int on_arg_id(int) { return ++num_parts, 0; } + FMT_CONSTEXPR int on_arg_id(basic_string_view) { + return ++num_parts, 0; + } + + FMT_CONSTEXPR void on_replacement_field(int, const Char*) {} + + FMT_CONSTEXPR const Char* on_format_specs(int, const Char* begin, + const Char* end) { + // Find the matching brace. + unsigned brace_counter = 0; + for (; begin != end; ++begin) { + if (*begin == '{') { + ++brace_counter; + } else if (*begin == '}') { + if (brace_counter == 0u) break; + --brace_counter; + } + } + return begin; + } + + FMT_CONSTEXPR void on_error(const char*) {} +}; + +// Counts the number of parts in a format string. +template +FMT_CONSTEXPR unsigned count_parts(basic_string_view format_str) { + part_counter counter; + parse_format_string(format_str, counter); + return counter.num_parts; +} + +template +class format_string_compiler : public error_handler { + private: + using part = format_part; + + PartHandler handler_; + part part_; + basic_string_view format_str_; + basic_format_parse_context parse_context_; + + public: + FMT_CONSTEXPR format_string_compiler(basic_string_view format_str, + PartHandler handler) + : handler_(handler), + format_str_(format_str), + parse_context_(format_str) {} + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + if (begin != end) + handler_(part::make_text({begin, to_unsigned(end - begin)})); + } + + FMT_CONSTEXPR int on_arg_id() { + part_ = part::make_arg_index(parse_context_.next_arg_id()); + return 0; + } + + FMT_CONSTEXPR int on_arg_id(int id) { + parse_context_.check_arg_id(id); + part_ = part::make_arg_index(id); + return 0; + } + + FMT_CONSTEXPR int on_arg_id(basic_string_view id) { + part_ = part::make_arg_name(id); + return 0; + } + + FMT_CONSTEXPR void on_replacement_field(int, const Char* ptr) { + part_.arg_id_end = ptr; + handler_(part_); + } + + FMT_CONSTEXPR const Char* on_format_specs(int, const Char* begin, + const Char* end) { + auto repl = typename part::replacement(); + dynamic_specs_handler> handler( + repl.specs, parse_context_); + auto it = parse_format_specs(begin, end, handler); + if (*it != '}') on_error("missing '}' in format string"); + repl.arg_id = part_.part_kind == part::kind::arg_index + ? arg_ref(part_.val.arg_index) + : arg_ref(part_.val.str); + auto part = part::make_replacement(repl); + part.arg_id_end = begin; + handler_(part); + return it; + } +}; + +// Compiles a format string and invokes handler(part) for each parsed part. +template +FMT_CONSTEXPR void compile_format_string(basic_string_view format_str, + PartHandler handler) { + parse_format_string( + format_str, + format_string_compiler(format_str, handler)); +} + +template +void format_arg( + basic_format_parse_context& parse_ctx, + Context& ctx, Id arg_id) { + ctx.advance_to(visit_format_arg( + arg_formatter(ctx, &parse_ctx), + ctx.arg(arg_id))); +} + +// vformat_to is defined in a subnamespace to prevent ADL. +namespace cf { +template +auto vformat_to(OutputIt out, CompiledFormat& cf, + basic_format_args args) -> typename Context::iterator { + using char_type = typename Context::char_type; + basic_format_parse_context parse_ctx( + to_string_view(cf.format_str_)); + Context ctx(out, args); + + const auto& parts = cf.parts(); + for (auto part_it = std::begin(parts); part_it != std::end(parts); + ++part_it) { + const auto& part = *part_it; + const auto& value = part.val; + + using format_part_t = format_part; + switch (part.part_kind) { + case format_part_t::kind::text: { + const auto text = value.str; + auto output = ctx.out(); + auto&& it = reserve(output, text.size()); + it = std::copy_n(text.begin(), text.size(), it); + ctx.advance_to(output); + break; + } + + case format_part_t::kind::arg_index: + advance_to(parse_ctx, part.arg_id_end); + detail::format_arg(parse_ctx, ctx, value.arg_index); + break; + + case format_part_t::kind::arg_name: + advance_to(parse_ctx, part.arg_id_end); + detail::format_arg(parse_ctx, ctx, value.str); + break; + + case format_part_t::kind::replacement: { + const auto& arg_id_value = value.repl.arg_id.val; + const auto arg = value.repl.arg_id.kind == arg_id_kind::index + ? ctx.arg(arg_id_value.index) + : ctx.arg(arg_id_value.name); + + auto specs = value.repl.specs; + + handle_dynamic_spec(specs.width, specs.width_ref, ctx); + handle_dynamic_spec(specs.precision, + specs.precision_ref, ctx); + + error_handler h; + numeric_specs_checker checker(h, arg.type()); + if (specs.align == align::numeric) checker.require_numeric_argument(); + if (specs.sign != sign::none) checker.check_sign(); + if (specs.alt) checker.require_numeric_argument(); + if (specs.precision >= 0) checker.check_precision(); + + advance_to(parse_ctx, part.arg_id_end); + ctx.advance_to( + visit_format_arg(arg_formatter( + ctx, nullptr, &specs), + arg)); + break; + } + } + } + return ctx.out(); +} +} // namespace cf + +struct basic_compiled_format {}; + +template +struct compiled_format_base : basic_compiled_format { + using char_type = char_t; + using parts_container = std::vector>; + + parts_container compiled_parts; + + explicit compiled_format_base(basic_string_view format_str) { + compile_format_string(format_str, + [this](const format_part& part) { + compiled_parts.push_back(part); + }); + } + + const parts_container& parts() const { return compiled_parts; } +}; + +template struct format_part_array { + format_part data[N] = {}; + FMT_CONSTEXPR format_part_array() = default; +}; + +template +FMT_CONSTEXPR format_part_array compile_to_parts( + basic_string_view format_str) { + format_part_array parts; + unsigned counter = 0; + // This is not a lambda for compatibility with older compilers. + struct { + format_part* parts; + unsigned* counter; + FMT_CONSTEXPR void operator()(const format_part& part) { + parts[(*counter)++] = part; + } + } collector{parts.data, &counter}; + compile_format_string(format_str, collector); + if (counter < N) { + parts.data[counter] = + format_part::make_text(basic_string_view()); + } + return parts; +} + +template constexpr const T& constexpr_max(const T& a, const T& b) { + return (a < b) ? b : a; +} + +template +struct compiled_format_base::value>> + : basic_compiled_format { + using char_type = char_t; + + FMT_CONSTEXPR explicit compiled_format_base(basic_string_view) {} + +// Workaround for old compilers. Format string compilation will not be +// performed there anyway. +#if FMT_USE_CONSTEXPR + static FMT_CONSTEXPR_DECL const unsigned num_format_parts = + constexpr_max(count_parts(to_string_view(S())), 1u); +#else + static const unsigned num_format_parts = 1; +#endif + + using parts_container = format_part[num_format_parts]; + + const parts_container& parts() const { + static FMT_CONSTEXPR_DECL const auto compiled_parts = + compile_to_parts( + detail::to_string_view(S())); + return compiled_parts.data; + } +}; + +template +class compiled_format : private compiled_format_base { + public: + using typename compiled_format_base::char_type; + + private: + basic_string_view format_str_; + + template + friend auto cf::vformat_to(OutputIt out, CompiledFormat& cf, + basic_format_args args) -> + typename Context::iterator; + + public: + compiled_format() = delete; + explicit constexpr compiled_format(basic_string_view format_str) + : compiled_format_base(format_str), format_str_(format_str) {} +}; + +#ifdef __cpp_if_constexpr +template struct type_list {}; + +// Returns a reference to the argument at index N from [first, rest...]. +template +constexpr const auto& get([[maybe_unused]] const T& first, + [[maybe_unused]] const Args&... rest) { + static_assert(N < 1 + sizeof...(Args), "index is out of bounds"); + if constexpr (N == 0) + return first; + else + return get(rest...); +} + +template struct get_type_impl; + +template struct get_type_impl> { + using type = remove_cvref_t(std::declval()...))>; +}; + +template +using get_type = typename get_type_impl::type; + +template struct is_compiled_format : std::false_type {}; + +template struct text { + basic_string_view data; + using char_type = Char; + + template + OutputIt format(OutputIt out, const Args&...) const { + return write(out, data); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template +constexpr text make_text(basic_string_view s, size_t pos, + size_t size) { + return {{&s[pos], size}}; +} + +template struct code_unit { + Char value; + using char_type = Char; + + template + OutputIt format(OutputIt out, const Args&...) const { + return write(out, value); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +// A replacement field that refers to argument N. +template struct field { + using char_type = Char; + + template + OutputIt format(OutputIt out, const Args&... args) const { + // This ensures that the argument type is convertile to `const T&`. + const T& arg = get(args...); + return write(out, arg); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +// A replacement field that refers to argument N and has format specifiers. +template struct spec_field { + using char_type = Char; + mutable formatter fmt; + + template + OutputIt format(OutputIt out, const Args&... args) const { + // This ensures that the argument type is convertile to `const T&`. + const T& arg = get(args...); + const auto& vargs = + make_format_args>(args...); + basic_format_context ctx(out, vargs); + return fmt.format(arg, ctx); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template struct concat { + L lhs; + R rhs; + using char_type = typename L::char_type; + + template + OutputIt format(OutputIt out, const Args&... args) const { + out = lhs.format(out, args...); + return rhs.format(out, args...); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template +constexpr concat make_concat(L lhs, R rhs) { + return {lhs, rhs}; +} + +struct unknown_format {}; + +template +constexpr size_t parse_text(basic_string_view str, size_t pos) { + for (size_t size = str.size(); pos != size; ++pos) { + if (str[pos] == '{' || str[pos] == '}') break; + } + return pos; +} + +template +constexpr auto compile_format_string(S format_str); + +template +constexpr auto parse_tail(T head, S format_str) { + if constexpr (POS != + basic_string_view(format_str).size()) { + constexpr auto tail = compile_format_string(format_str); + if constexpr (std::is_same, + unknown_format>()) + return tail; + else + return make_concat(head, tail); + } else { + return head; + } +} + +template struct parse_specs_result { + formatter fmt; + size_t end; + int next_arg_id; +}; + +template +constexpr parse_specs_result parse_specs(basic_string_view str, + size_t pos, int arg_id) { + str.remove_prefix(pos); + auto ctx = basic_format_parse_context(str, {}, arg_id + 1); + auto f = formatter(); + auto end = f.parse(ctx); + return {f, pos + (end - str.data()) + 1, ctx.next_arg_id()}; +} + +// Compiles a non-empty format string and returns the compiled representation +// or unknown_format() on unrecognized input. +template +constexpr auto compile_format_string(S format_str) { + using char_type = typename S::char_type; + constexpr basic_string_view str = format_str; + if constexpr (str[POS] == '{') { + if (POS + 1 == str.size()) + throw format_error("unmatched '{' in format string"); + if constexpr (str[POS + 1] == '{') { + return parse_tail(make_text(str, POS, 1), format_str); + } else if constexpr (str[POS + 1] == '}') { + using type = get_type; + return parse_tail(field(), + format_str); + } else if constexpr (str[POS + 1] == ':') { + using type = get_type; + constexpr auto result = parse_specs(str, POS + 2, ID); + return parse_tail( + spec_field{result.fmt}, format_str); + } else { + return unknown_format(); + } + } else if constexpr (str[POS] == '}') { + if (POS + 1 == str.size()) + throw format_error("unmatched '}' in format string"); + return parse_tail(make_text(str, POS, 1), format_str); + } else { + constexpr auto end = parse_text(str, POS + 1); + if constexpr (end - POS > 1) { + return parse_tail(make_text(str, POS, end - POS), + format_str); + } else { + return parse_tail(code_unit{str[POS]}, + format_str); + } + } +} + +template ::value || + detail::is_compiled_string::value)> +constexpr auto compile(S format_str) { + constexpr basic_string_view str = format_str; + if constexpr (str.size() == 0) { + return detail::make_text(str, 0, 0); + } else { + constexpr auto result = + detail::compile_format_string, 0, 0>( + format_str); + if constexpr (std::is_same, + detail::unknown_format>()) { + return detail::compiled_format(to_string_view(format_str)); + } else { + return result; + } + } +} +#else +template ::value)> +constexpr auto compile(S format_str) -> detail::compiled_format { + return detail::compiled_format(to_string_view(format_str)); +} +#endif // __cpp_if_constexpr + +// Compiles the format string which must be a string literal. +template +auto compile(const Char (&format_str)[N]) + -> detail::compiled_format { + return detail::compiled_format( + basic_string_view(format_str, N - 1)); +} +} // namespace detail + +// DEPRECATED! use FMT_COMPILE instead. +template +FMT_DEPRECATED auto compile(const Args&... args) + -> decltype(detail::compile(args...)) { + return detail::compile(args...); +} + +#if FMT_USE_CONSTEXPR +# ifdef __cpp_if_constexpr + +template ::value)> +FMT_INLINE std::basic_string format(const CompiledFormat& cf, + const Args&... args) { + basic_memory_buffer buffer; + cf.format(detail::buffer_appender(buffer), args...); + return to_string(buffer); +} + +template ::value)> +OutputIt format_to(OutputIt out, const CompiledFormat& cf, + const Args&... args) { + return cf.format(out, args...); +} +# endif // __cpp_if_constexpr +#endif // FMT_USE_CONSTEXPR + +template ::value)> +std::basic_string format(const CompiledFormat& cf, const Args&... args) { + basic_memory_buffer buffer; + using context = buffer_context; + detail::cf::vformat_to(detail::buffer_appender(buffer), cf, + make_format_args(args...)); + return to_string(buffer); +} + +template ::value)> +FMT_INLINE std::basic_string format(const S&, + Args&&... args) { +#ifdef __cpp_if_constexpr + if constexpr (std::is_same::value) { + constexpr basic_string_view str = S(); + if (str.size() == 2 && str[0] == '{' && str[1] == '}') + return fmt::to_string(detail::first(args...)); + } +#endif + constexpr auto compiled = detail::compile(S()); + return format(compiled, std::forward(args)...); +} + +template ::value)> +OutputIt format_to(OutputIt out, const CompiledFormat& cf, + const Args&... args) { + using char_type = typename CompiledFormat::char_type; + using context = format_context_t; + return detail::cf::vformat_to(out, cf, + make_format_args(args...)); +} + +template ::value)> +OutputIt format_to(OutputIt out, const S&, const Args&... args) { + constexpr auto compiled = detail::compile(S()); + return format_to(out, compiled, args...); +} + +template < + typename OutputIt, typename CompiledFormat, typename... Args, + FMT_ENABLE_IF(detail::is_output_iterator::value&& std::is_base_of< + detail::basic_compiled_format, CompiledFormat>::value)> +format_to_n_result format_to_n(OutputIt out, size_t n, + const CompiledFormat& cf, + const Args&... args) { + auto it = + format_to(detail::truncating_iterator(out, n), cf, args...); + return {it.base(), it.count()}; +} + +template ::value)> +format_to_n_result format_to_n(OutputIt out, size_t n, const S&, + const Args&... args) { + constexpr auto compiled = detail::compile(S()); + auto it = format_to(detail::truncating_iterator(out, n), compiled, + args...); + return {it.base(), it.count()}; +} + +template +size_t formatted_size(const CompiledFormat& cf, const Args&... args) { + return format_to(detail::counting_iterator(), cf, args...).count(); +} + +FMT_END_NAMESPACE + +#endif // FMT_COMPILE_H_ diff --git a/src/3rdparty/fmt/core.h b/src/3rdparty/fmt/core.h new file mode 100644 index 00000000..2e1ae4b6 --- /dev/null +++ b/src/3rdparty/fmt/core.h @@ -0,0 +1,2129 @@ +// Formatting library for C++ - the core API +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CORE_H_ +#define FMT_CORE_H_ + +#include // std::FILE +#include +#include +#include +#include +#include +#include +#include + +// The fmt library version in the form major * 10000 + minor * 100 + patch. +#define FMT_VERSION 70003 + +#ifdef __clang__ +# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#else +# define FMT_CLANG_VERSION 0 +#endif + +#if defined(__GNUC__) && !defined(__clang__) +# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#else +# define FMT_GCC_VERSION 0 +#endif + +#if defined(__INTEL_COMPILER) +# define FMT_ICC_VERSION __INTEL_COMPILER +#else +# define FMT_ICC_VERSION 0 +#endif + +#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) +# define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION +#else +# define FMT_HAS_GXX_CXX11 0 +#endif + +#ifdef __NVCC__ +# define FMT_NVCC __NVCC__ +#else +# define FMT_NVCC 0 +#endif + +#ifdef _MSC_VER +# define FMT_MSC_VER _MSC_VER +# define FMT_SUPPRESS_MSC_WARNING(n) __pragma(warning(suppress : n)) +#else +# define FMT_MSC_VER 0 +# define FMT_SUPPRESS_MSC_WARNING(n) +#endif + +#ifdef __has_feature +# define FMT_HAS_FEATURE(x) __has_feature(x) +#else +# define FMT_HAS_FEATURE(x) 0 +#endif + +#if defined(__has_include) && !defined(__INTELLISENSE__) && \ + (!FMT_ICC_VERSION || FMT_ICC_VERSION >= 1600) +# define FMT_HAS_INCLUDE(x) __has_include(x) +#else +# define FMT_HAS_INCLUDE(x) 0 +#endif + +#ifdef __has_cpp_attribute +# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define FMT_HAS_CPP_ATTRIBUTE(x) 0 +#endif + +#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \ + (__cplusplus >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \ + (__cplusplus >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +// Check if relaxed C++14 constexpr is supported. +// GCC doesn't allow throw in constexpr until version 6 (bug 67371). +#ifndef FMT_USE_CONSTEXPR +# define FMT_USE_CONSTEXPR \ + (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \ + (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) && \ + !FMT_NVCC && !FMT_ICC_VERSION +#endif +#if FMT_USE_CONSTEXPR +# define FMT_CONSTEXPR constexpr +# define FMT_CONSTEXPR_DECL constexpr +#else +# define FMT_CONSTEXPR inline +# define FMT_CONSTEXPR_DECL +#endif + +#ifndef FMT_OVERRIDE +# if FMT_HAS_FEATURE(cxx_override_control) || \ + (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 +# define FMT_OVERRIDE override +# else +# define FMT_OVERRIDE +# endif +#endif + +// Check if exceptions are disabled. +#ifndef FMT_EXCEPTIONS +# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \ + FMT_MSC_VER && !_HAS_EXCEPTIONS +# define FMT_EXCEPTIONS 0 +# else +# define FMT_EXCEPTIONS 1 +# endif +#endif + +// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). +#ifndef FMT_USE_NOEXCEPT +# define FMT_USE_NOEXCEPT 0 +#endif + +#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ + (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 +# define FMT_DETECTED_NOEXCEPT noexcept +# define FMT_HAS_CXX11_NOEXCEPT 1 +#else +# define FMT_DETECTED_NOEXCEPT throw() +# define FMT_HAS_CXX11_NOEXCEPT 0 +#endif + +#ifndef FMT_NOEXCEPT +# if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT +# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT +# else +# define FMT_NOEXCEPT +# endif +#endif + +// [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code +// warnings. +#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER && \ + !FMT_NVCC +# define FMT_NORETURN [[noreturn]] +#else +# define FMT_NORETURN +#endif + +#ifndef FMT_DEPRECATED +# if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VER >= 1900 +# define FMT_DEPRECATED [[deprecated]] +# else +# if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__) +# define FMT_DEPRECATED __attribute__((deprecated)) +# elif FMT_MSC_VER +# define FMT_DEPRECATED __declspec(deprecated) +# else +# define FMT_DEPRECATED /* deprecated */ +# endif +# endif +#endif + +// Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers. +#if FMT_ICC_VERSION || defined(__PGI) || FMT_NVCC +# define FMT_DEPRECATED_ALIAS +#else +# define FMT_DEPRECATED_ALIAS FMT_DEPRECATED +#endif + +#ifndef FMT_INLINE +# if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_INLINE inline __attribute__((always_inline)) +# else +# define FMT_INLINE inline +# endif +#endif + +#ifndef FMT_BEGIN_NAMESPACE +# if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \ + (FMT_MSC_VER >= 1900 && !_MANAGED) +# define FMT_INLINE_NAMESPACE inline namespace +# define FMT_END_NAMESPACE \ + } \ + } +# else +# define FMT_INLINE_NAMESPACE namespace +# define FMT_END_NAMESPACE \ + } \ + using namespace v7; \ + } +# endif +# define FMT_BEGIN_NAMESPACE \ + namespace fmt { \ + FMT_INLINE_NAMESPACE v7 { +#endif + +#if !defined(FMT_HEADER_ONLY) && defined(_WIN32) +# define FMT_CLASS_API FMT_SUPPRESS_MSC_WARNING(4275) +# ifdef FMT_EXPORT +# define FMT_API __declspec(dllexport) +# define FMT_EXTERN_TEMPLATE_API FMT_API +# define FMT_EXPORTED +# elif defined(FMT_SHARED) +# define FMT_API __declspec(dllimport) +# define FMT_EXTERN_TEMPLATE_API FMT_API +# endif +#else +# define FMT_CLASS_API +#endif +#ifndef FMT_API +# define FMT_API +#endif +#ifndef FMT_EXTERN_TEMPLATE_API +# define FMT_EXTERN_TEMPLATE_API +#endif +#ifndef FMT_INSTANTIATION_DEF_API +# define FMT_INSTANTIATION_DEF_API FMT_API +#endif + +#ifndef FMT_HEADER_ONLY +# define FMT_EXTERN extern +#else +# define FMT_EXTERN +#endif + +// libc++ supports string_view in pre-c++17. +#if (FMT_HAS_INCLUDE() && \ + (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \ + (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) +# include +# define FMT_USE_STRING_VIEW +#elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L +# include +# define FMT_USE_EXPERIMENTAL_STRING_VIEW +#endif + +#ifndef FMT_UNICODE +# define FMT_UNICODE !FMT_MSC_VER +#endif +#if FMT_UNICODE && FMT_MSC_VER +# pragma execution_character_set("utf-8") +#endif + +FMT_BEGIN_NAMESPACE + +// Implementations of enable_if_t and other metafunctions for older systems. +template +using enable_if_t = typename std::enable_if::type; +template +using conditional_t = typename std::conditional::type; +template using bool_constant = std::integral_constant; +template +using remove_reference_t = typename std::remove_reference::type; +template +using remove_const_t = typename std::remove_const::type; +template +using remove_cvref_t = typename std::remove_cv>::type; +template struct type_identity { using type = T; }; +template using type_identity_t = typename type_identity::type; + +struct monostate {}; + +// An enable_if helper to be used in template parameters which results in much +// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed +// to workaround a bug in MSVC 2019 (see #1140 and #1186). +#define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0 + +namespace detail { + +// A helper function to suppress "conditional expression is constant" warnings. +template constexpr T const_check(T value) { return value; } + +FMT_NORETURN FMT_API void assert_fail(const char* file, int line, + const char* message); + +#ifndef FMT_ASSERT +# ifdef NDEBUG +// FMT_ASSERT is not empty to avoid -Werror=empty-body. +# define FMT_ASSERT(condition, message) ((void)0) +# else +# define FMT_ASSERT(condition, message) \ + ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \ + ? (void)0 \ + : ::fmt::detail::assert_fail(__FILE__, __LINE__, (message))) +# endif +#endif + +#if defined(FMT_USE_STRING_VIEW) +template using std_string_view = std::basic_string_view; +#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) +template +using std_string_view = std::experimental::basic_string_view; +#else +template struct std_string_view {}; +#endif + +#ifdef FMT_USE_INT128 +// Do nothing. +#elif defined(__SIZEOF_INT128__) && !FMT_NVCC && \ + !(FMT_CLANG_VERSION && FMT_MSC_VER) +# define FMT_USE_INT128 1 +using int128_t = __int128_t; +using uint128_t = __uint128_t; +#else +# define FMT_USE_INT128 0 +#endif +#if !FMT_USE_INT128 +struct int128_t {}; +struct uint128_t {}; +#endif + +// Casts a nonnegative integer to unsigned. +template +FMT_CONSTEXPR typename std::make_unsigned::type to_unsigned(Int value) { + FMT_ASSERT(value >= 0, "negative value"); + return static_cast::type>(value); +} + +FMT_SUPPRESS_MSC_WARNING(4566) constexpr unsigned char micro[] = "\u00B5"; + +template constexpr bool is_unicode() { + return FMT_UNICODE || sizeof(Char) != 1 || + (sizeof(micro) == 3 && micro[0] == 0xC2 && micro[1] == 0xB5); +} + +#ifdef __cpp_char8_t +using char8_type = char8_t; +#else +enum char8_type : unsigned char {}; +#endif +} // namespace detail + +#ifdef FMT_USE_INTERNAL +namespace internal = detail; // DEPRECATED +#endif + +/** + An implementation of ``std::basic_string_view`` for pre-C++17. It provides a + subset of the API. ``fmt::basic_string_view`` is used for format strings even + if ``std::string_view`` is available to prevent issues when a library is + compiled with a different ``-std`` option than the client code (which is not + recommended). + */ +template class basic_string_view { + private: + const Char* data_; + size_t size_; + + public: + using value_type = Char; + using iterator = const Char*; + + constexpr basic_string_view() FMT_NOEXCEPT : data_(nullptr), size_(0) {} + + /** Constructs a string reference object from a C string and a size. */ + constexpr basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT + : data_(s), + size_(count) {} + + /** + \rst + Constructs a string reference object from a C string computing + the size with ``std::char_traits::length``. + \endrst + */ +#if __cplusplus >= 201703L // C++17's char_traits::length() is constexpr. + FMT_CONSTEXPR +#endif + basic_string_view(const Char* s) + : data_(s), size_(std::char_traits::length(s)) {} + + /** Constructs a string reference from a ``std::basic_string`` object. */ + template + FMT_CONSTEXPR basic_string_view( + const std::basic_string& s) FMT_NOEXCEPT + : data_(s.data()), + size_(s.size()) {} + + template >::value)> + FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()), + size_(s.size()) {} + + /** Returns a pointer to the string data. */ + constexpr const Char* data() const { return data_; } + + /** Returns the string size. */ + constexpr size_t size() const { return size_; } + + constexpr iterator begin() const { return data_; } + constexpr iterator end() const { return data_ + size_; } + + constexpr const Char& operator[](size_t pos) const { return data_[pos]; } + + FMT_CONSTEXPR void remove_prefix(size_t n) { + data_ += n; + size_ -= n; + } + + // Lexicographically compare this string reference to other. + int compare(basic_string_view other) const { + size_t str_size = size_ < other.size_ ? size_ : other.size_; + int result = std::char_traits::compare(data_, other.data_, str_size); + if (result == 0) + result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); + return result; + } + + friend bool operator==(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) == 0; + } + friend bool operator!=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) != 0; + } + friend bool operator<(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) < 0; + } + friend bool operator<=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) <= 0; + } + friend bool operator>(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) > 0; + } + friend bool operator>=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) >= 0; + } +}; + +using string_view = basic_string_view; +using wstring_view = basic_string_view; + +/** Specifies if ``T`` is a character type. Can be specialized by users. */ +template struct is_char : std::false_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; +template <> struct is_char : std::true_type {}; + +/** + \rst + Returns a string view of `s`. In order to add custom string type support to + {fmt} provide an overload of `to_string_view` for it in the same namespace as + the type for the argument-dependent lookup to work. + + **Example**:: + + namespace my_ns { + inline string_view to_string_view(const my_string& s) { + return {s.data(), s.length()}; + } + } + std::string message = fmt::format(my_string("The answer is {}"), 42); + \endrst + */ +template ::value)> +inline basic_string_view to_string_view(const Char* s) { + return s; +} + +template +inline basic_string_view to_string_view( + const std::basic_string& s) { + return s; +} + +template +inline basic_string_view to_string_view(basic_string_view s) { + return s; +} + +template >::value)> +inline basic_string_view to_string_view(detail::std_string_view s) { + return s; +} + +// A base class for compile-time strings. It is defined in the fmt namespace to +// make formatting functions visible via ADL, e.g. format(FMT_STRING("{}"), 42). +struct compile_string {}; + +template +struct is_compile_string : std::is_base_of {}; + +template ::value)> +constexpr basic_string_view to_string_view(const S& s) { + return s; +} + +namespace detail { +void to_string_view(...); +using fmt::v7::to_string_view; + +// Specifies whether S is a string type convertible to fmt::basic_string_view. +// It should be a constexpr function but MSVC 2017 fails to compile it in +// enable_if and MSVC 2015 fails to compile it as an alias template. +template +struct is_string : std::is_class()))> { +}; + +template struct char_t_impl {}; +template struct char_t_impl::value>> { + using result = decltype(to_string_view(std::declval())); + using type = typename result::value_type; +}; + +// Reports a compile-time error if S is not a valid format string. +template ::value)> +FMT_INLINE void check_format_string(const S&) { +#ifdef FMT_ENFORCE_COMPILE_STRING + static_assert(is_compile_string::value, + "FMT_ENFORCE_COMPILE_STRING requires all format strings to use " + "FMT_STRING."); +#endif +} +template ::value)> +void check_format_string(S); + +struct error_handler { + constexpr error_handler() = default; + constexpr error_handler(const error_handler&) = default; + + // This function is intentionally not constexpr to give a compile-time error. + FMT_NORETURN FMT_API void on_error(const char* message); +}; +} // namespace detail + +/** String's character type. */ +template using char_t = typename detail::char_t_impl::type; + +/** + \rst + Parsing context consisting of a format string range being parsed and an + argument counter for automatic indexing. + + You can use one of the following type aliases for common character types: + + +-----------------------+-------------------------------------+ + | Type | Definition | + +=======================+=====================================+ + | format_parse_context | basic_format_parse_context | + +-----------------------+-------------------------------------+ + | wformat_parse_context | basic_format_parse_context | + +-----------------------+-------------------------------------+ + \endrst + */ +template +class basic_format_parse_context : private ErrorHandler { + private: + basic_string_view format_str_; + int next_arg_id_; + + public: + using char_type = Char; + using iterator = typename basic_string_view::iterator; + + explicit constexpr basic_format_parse_context( + basic_string_view format_str, ErrorHandler eh = {}, + int next_arg_id = 0) + : ErrorHandler(eh), format_str_(format_str), next_arg_id_(next_arg_id) {} + + /** + Returns an iterator to the beginning of the format string range being + parsed. + */ + constexpr iterator begin() const FMT_NOEXCEPT { return format_str_.begin(); } + + /** + Returns an iterator past the end of the format string range being parsed. + */ + constexpr iterator end() const FMT_NOEXCEPT { return format_str_.end(); } + + /** Advances the begin iterator to ``it``. */ + FMT_CONSTEXPR void advance_to(iterator it) { + format_str_.remove_prefix(detail::to_unsigned(it - begin())); + } + + /** + Reports an error if using the manual argument indexing; otherwise returns + the next argument index and switches to the automatic indexing. + */ + FMT_CONSTEXPR int next_arg_id() { + // Don't check if the argument id is valid to avoid overhead and because it + // will be checked during formatting anyway. + if (next_arg_id_ >= 0) return next_arg_id_++; + on_error("cannot switch from manual to automatic argument indexing"); + return 0; + } + + /** + Reports an error if using the automatic argument indexing; otherwise + switches to the manual indexing. + */ + FMT_CONSTEXPR void check_arg_id(int) { + if (next_arg_id_ > 0) + on_error("cannot switch from automatic to manual argument indexing"); + else + next_arg_id_ = -1; + } + + FMT_CONSTEXPR void check_arg_id(basic_string_view) {} + + FMT_CONSTEXPR void on_error(const char* message) { + ErrorHandler::on_error(message); + } + + constexpr ErrorHandler error_handler() const { return *this; } +}; + +using format_parse_context = basic_format_parse_context; +using wformat_parse_context = basic_format_parse_context; + +template class basic_format_arg; +template class basic_format_args; +template class dynamic_format_arg_store; + +// A formatter for objects of type T. +template +struct formatter { + // A deleted default constructor indicates a disabled formatter. + formatter() = delete; +}; + +// Specifies if T has an enabled formatter specialization. A type can be +// formattable even if it doesn't have a formatter e.g. via a conversion. +template +using has_formatter = + std::is_constructible>; + +// Checks whether T is a container with contiguous storage. +template struct is_contiguous : std::false_type {}; +template +struct is_contiguous> : std::true_type {}; + +namespace detail { + +// Extracts a reference to the container from back_insert_iterator. +template +inline Container& get_container(std::back_insert_iterator it) { + using bi_iterator = std::back_insert_iterator; + struct accessor : bi_iterator { + accessor(bi_iterator iter) : bi_iterator(iter) {} + using bi_iterator::container; + }; + return *accessor(it).container; +} + +/** + \rst + A contiguous memory buffer with an optional growing ability. It is an internal + class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`. + \endrst + */ +template class buffer { + private: + T* ptr_; + size_t size_; + size_t capacity_; + + protected: + // Don't initialize ptr_ since it is not accessed to save a few cycles. + FMT_SUPPRESS_MSC_WARNING(26495) + buffer(size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {} + + buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) FMT_NOEXCEPT + : ptr_(p), + size_(sz), + capacity_(cap) {} + + ~buffer() = default; + + /** Sets the buffer data and capacity. */ + void set(T* buf_data, size_t buf_capacity) FMT_NOEXCEPT { + ptr_ = buf_data; + capacity_ = buf_capacity; + } + + /** Increases the buffer capacity to hold at least *capacity* elements. */ + virtual void grow(size_t capacity) = 0; + + public: + using value_type = T; + using const_reference = const T&; + + buffer(const buffer&) = delete; + void operator=(const buffer&) = delete; + + T* begin() FMT_NOEXCEPT { return ptr_; } + T* end() FMT_NOEXCEPT { return ptr_ + size_; } + + const T* begin() const FMT_NOEXCEPT { return ptr_; } + const T* end() const FMT_NOEXCEPT { return ptr_ + size_; } + + /** Returns the size of this buffer. */ + size_t size() const FMT_NOEXCEPT { return size_; } + + /** Returns the capacity of this buffer. */ + size_t capacity() const FMT_NOEXCEPT { return capacity_; } + + /** Returns a pointer to the buffer data. */ + T* data() FMT_NOEXCEPT { return ptr_; } + + /** Returns a pointer to the buffer data. */ + const T* data() const FMT_NOEXCEPT { return ptr_; } + + /** Clears this buffer. */ + void clear() { size_ = 0; } + + // Tries resizing the buffer to contain *count* elements. If T is a POD type + // the new elements may not be initialized. + void try_resize(size_t count) { + try_reserve(count); + size_ = count <= capacity_ ? count : capacity_; + } + + // Tries increasing the buffer capacity to *new_capacity*. It can increase the + // capacity by a smaller amount than requested but guarantees there is space + // for at least one additional element either by increasing the capacity or by + // flushing the buffer if it is full. + void try_reserve(size_t new_capacity) { + if (new_capacity > capacity_) grow(new_capacity); + } + + void push_back(const T& value) { + try_reserve(size_ + 1); + ptr_[size_++] = value; + } + + /** Appends data to the end of the buffer. */ + template void append(const U* begin, const U* end); + + template T& operator[](I index) { return ptr_[index]; } + template const T& operator[](I index) const { + return ptr_[index]; + } +}; + +struct buffer_traits { + explicit buffer_traits(size_t) {} + size_t count() const { return 0; } + size_t limit(size_t size) { return size; } +}; + +class fixed_buffer_traits { + private: + size_t count_ = 0; + size_t limit_; + + public: + explicit fixed_buffer_traits(size_t limit) : limit_(limit) {} + size_t count() const { return count_; } + size_t limit(size_t size) { + size_t n = limit_ - count_; + count_ += size; + return size < n ? size : n; + } +}; + +// A buffer that writes to an output iterator when flushed. +template +class iterator_buffer : public Traits, public buffer { + private: + OutputIt out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + protected: + void grow(size_t) final FMT_OVERRIDE { + if (this->size() == buffer_size) flush(); + } + void flush(); + + public: + explicit iterator_buffer(OutputIt out, size_t n = buffer_size) + : Traits(n), + buffer(data_, 0, n < size_t(buffer_size) ? n : size_t(buffer_size)), + out_(out) {} + ~iterator_buffer() { flush(); } + + OutputIt out() { + flush(); + return out_; + } + size_t count() const { return Traits::count() + this->size(); } +}; + +template class iterator_buffer : public buffer { + protected: + void grow(size_t) final FMT_OVERRIDE {} + + public: + explicit iterator_buffer(T* out, size_t = 0) : buffer(out, 0, ~size_t()) {} + + T* out() { return &*this->end(); } +}; + +// A buffer that writes to a container with the contiguous storage. +template +class iterator_buffer, + enable_if_t::value, + typename Container::value_type>> + : public buffer { + private: + Container& container_; + + protected: + void grow(size_t capacity) final FMT_OVERRIDE { + container_.resize(capacity); + this->set(&container_[0], capacity); + } + + public: + explicit iterator_buffer(Container& c) + : buffer(c.size()), container_(c) {} + explicit iterator_buffer(std::back_insert_iterator out, size_t = 0) + : iterator_buffer(get_container(out)) {} + std::back_insert_iterator out() { + return std::back_inserter(container_); + } +}; + +// A buffer that counts the number of code units written discarding the output. +template class counting_buffer : public buffer { + private: + enum { buffer_size = 256 }; + T data_[buffer_size]; + size_t count_ = 0; + + protected: + void grow(size_t) final FMT_OVERRIDE { + if (this->size() != buffer_size) return; + count_ += this->size(); + this->clear(); + } + + public: + counting_buffer() : buffer(data_, 0, buffer_size) {} + + size_t count() { return count_ + this->size(); } +}; + +// An output iterator that appends to the buffer. +// It is used to reduce symbol sizes for the common case. +template +class buffer_appender : public std::back_insert_iterator> { + using base = std::back_insert_iterator>; + + public: + explicit buffer_appender(buffer& buf) : base(buf) {} + buffer_appender(base it) : base(it) {} + + buffer_appender& operator++() { + base::operator++(); + return *this; + } + + buffer_appender operator++(int) { + buffer_appender tmp = *this; + ++*this; + return tmp; + } +}; + +// Maps an output iterator into a buffer. +template +iterator_buffer get_buffer(OutputIt); +template buffer& get_buffer(buffer_appender); + +template OutputIt get_buffer_init(OutputIt out) { + return out; +} +template buffer& get_buffer_init(buffer_appender out) { + return get_container(out); +} + +template +auto get_iterator(Buffer& buf) -> decltype(buf.out()) { + return buf.out(); +} +template buffer_appender get_iterator(buffer& buf) { + return buffer_appender(buf); +} + +template +struct fallback_formatter { + fallback_formatter() = delete; +}; + +// Specifies if T has an enabled fallback_formatter specialization. +template +using has_fallback_formatter = + std::is_constructible>; + +struct view {}; + +template struct named_arg : view { + const Char* name; + const T& value; + named_arg(const Char* n, const T& v) : name(n), value(v) {} +}; + +template struct named_arg_info { + const Char* name; + int id; +}; + +template +struct arg_data { + // args_[0].named_args points to named_args_ to avoid bloating format_args. + // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. + T args_[1 + (NUM_ARGS != 0 ? NUM_ARGS : +1)]; + named_arg_info named_args_[NUM_NAMED_ARGS]; + + template + arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {} + arg_data(const arg_data& other) = delete; + const T* args() const { return args_ + 1; } + named_arg_info* named_args() { return named_args_; } +}; + +template +struct arg_data { + // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. + T args_[NUM_ARGS != 0 ? NUM_ARGS : +1]; + + template + FMT_INLINE arg_data(const U&... init) : args_{init...} {} + FMT_INLINE const T* args() const { return args_; } + FMT_INLINE std::nullptr_t named_args() { return nullptr; } +}; + +template +inline void init_named_args(named_arg_info*, int, int) {} + +template +void init_named_args(named_arg_info* named_args, int arg_count, + int named_arg_count, const T&, const Tail&... args) { + init_named_args(named_args, arg_count + 1, named_arg_count, args...); +} + +template +void init_named_args(named_arg_info* named_args, int arg_count, + int named_arg_count, const named_arg& arg, + const Tail&... args) { + named_args[named_arg_count++] = {arg.name, arg_count}; + init_named_args(named_args, arg_count + 1, named_arg_count, args...); +} + +template +FMT_INLINE void init_named_args(std::nullptr_t, int, int, const Args&...) {} + +template struct is_named_arg : std::false_type {}; + +template +struct is_named_arg> : std::true_type {}; + +template constexpr size_t count() { return B ? 1 : 0; } +template constexpr size_t count() { + return (B1 ? 1 : 0) + count(); +} + +template constexpr size_t count_named_args() { + return count::value...>(); +} + +enum class type { + none_type, + // Integer types should go first, + int_type, + uint_type, + long_long_type, + ulong_long_type, + int128_type, + uint128_type, + bool_type, + char_type, + last_integer_type = char_type, + // followed by floating-point types. + float_type, + double_type, + long_double_type, + last_numeric_type = long_double_type, + cstring_type, + string_type, + pointer_type, + custom_type +}; + +// Maps core type T to the corresponding type enum constant. +template +struct type_constant : std::integral_constant {}; + +#define FMT_TYPE_CONSTANT(Type, constant) \ + template \ + struct type_constant \ + : std::integral_constant {} + +FMT_TYPE_CONSTANT(int, int_type); +FMT_TYPE_CONSTANT(unsigned, uint_type); +FMT_TYPE_CONSTANT(long long, long_long_type); +FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); +FMT_TYPE_CONSTANT(int128_t, int128_type); +FMT_TYPE_CONSTANT(uint128_t, uint128_type); +FMT_TYPE_CONSTANT(bool, bool_type); +FMT_TYPE_CONSTANT(Char, char_type); +FMT_TYPE_CONSTANT(float, float_type); +FMT_TYPE_CONSTANT(double, double_type); +FMT_TYPE_CONSTANT(long double, long_double_type); +FMT_TYPE_CONSTANT(const Char*, cstring_type); +FMT_TYPE_CONSTANT(basic_string_view, string_type); +FMT_TYPE_CONSTANT(const void*, pointer_type); + +constexpr bool is_integral_type(type t) { + return t > type::none_type && t <= type::last_integer_type; +} + +constexpr bool is_arithmetic_type(type t) { + return t > type::none_type && t <= type::last_numeric_type; +} + +template struct string_value { + const Char* data; + size_t size; +}; + +template struct named_arg_value { + const named_arg_info* data; + size_t size; +}; + +template struct custom_value { + using parse_context = typename Context::parse_context_type; + const void* value; + void (*format)(const void* arg, parse_context& parse_ctx, Context& ctx); +}; + +// A formatting argument value. +template class value { + public: + using char_type = typename Context::char_type; + + union { + int int_value; + unsigned uint_value; + long long long_long_value; + unsigned long long ulong_long_value; + int128_t int128_value; + uint128_t uint128_value; + bool bool_value; + char_type char_value; + float float_value; + double double_value; + long double long_double_value; + const void* pointer; + string_value string; + custom_value custom; + named_arg_value named_args; + }; + + constexpr FMT_INLINE value(int val = 0) : int_value(val) {} + constexpr FMT_INLINE value(unsigned val) : uint_value(val) {} + FMT_INLINE value(long long val) : long_long_value(val) {} + FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {} + FMT_INLINE value(int128_t val) : int128_value(val) {} + FMT_INLINE value(uint128_t val) : uint128_value(val) {} + FMT_INLINE value(float val) : float_value(val) {} + FMT_INLINE value(double val) : double_value(val) {} + FMT_INLINE value(long double val) : long_double_value(val) {} + FMT_INLINE value(bool val) : bool_value(val) {} + FMT_INLINE value(char_type val) : char_value(val) {} + FMT_INLINE value(const char_type* val) { string.data = val; } + FMT_INLINE value(basic_string_view val) { + string.data = val.data(); + string.size = val.size(); + } + FMT_INLINE value(const void* val) : pointer(val) {} + FMT_INLINE value(const named_arg_info* args, size_t size) + : named_args{args, size} {} + + template FMT_INLINE value(const T& val) { + custom.value = &val; + // Get the formatter type through the context to allow different contexts + // have different extension points, e.g. `formatter` for `format` and + // `printf_formatter` for `printf`. + custom.format = format_custom_arg< + T, conditional_t::value, + typename Context::template formatter_type, + fallback_formatter>>; + } + + private: + // Formats an argument of a custom type, such as a user-defined class. + template + static void format_custom_arg(const void* arg, + typename Context::parse_context_type& parse_ctx, + Context& ctx) { + Formatter f; + parse_ctx.advance_to(f.parse(parse_ctx)); + ctx.advance_to(f.format(*static_cast(arg), ctx)); + } +}; + +template +FMT_CONSTEXPR basic_format_arg make_arg(const T& value); + +// To minimize the number of types we need to deal with, long is translated +// either to int or to long long depending on its size. +enum { long_short = sizeof(long) == sizeof(int) }; +using long_type = conditional_t; +using ulong_type = conditional_t; + +struct unformattable {}; + +// Maps formatting arguments to core types. +template struct arg_mapper { + using char_type = typename Context::char_type; + + FMT_CONSTEXPR int map(signed char val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned char val) { return val; } + FMT_CONSTEXPR int map(short val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned short val) { return val; } + FMT_CONSTEXPR int map(int val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned val) { return val; } + FMT_CONSTEXPR long_type map(long val) { return val; } + FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; } + FMT_CONSTEXPR long long map(long long val) { return val; } + FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; } + FMT_CONSTEXPR int128_t map(int128_t val) { return val; } + FMT_CONSTEXPR uint128_t map(uint128_t val) { return val; } + FMT_CONSTEXPR bool map(bool val) { return val; } + + template ::value)> + FMT_CONSTEXPR char_type map(T val) { + static_assert( + std::is_same::value || std::is_same::value, + "mixing character types is disallowed"); + return val; + } + + FMT_CONSTEXPR float map(float val) { return val; } + FMT_CONSTEXPR double map(double val) { return val; } + FMT_CONSTEXPR long double map(long double val) { return val; } + + FMT_CONSTEXPR const char_type* map(char_type* val) { return val; } + FMT_CONSTEXPR const char_type* map(const char_type* val) { return val; } + template ::value)> + FMT_CONSTEXPR basic_string_view map(const T& val) { + static_assert(std::is_same>::value, + "mixing character types is disallowed"); + return to_string_view(val); + } + template , T>::value && + !is_string::value && !has_formatter::value && + !has_fallback_formatter::value)> + FMT_CONSTEXPR basic_string_view map(const T& val) { + return basic_string_view(val); + } + template < + typename T, + FMT_ENABLE_IF( + std::is_constructible, T>::value && + !std::is_constructible, T>::value && + !is_string::value && !has_formatter::value && + !has_fallback_formatter::value)> + FMT_CONSTEXPR basic_string_view map(const T& val) { + return std_string_view(val); + } + FMT_CONSTEXPR const char* map(const signed char* val) { + static_assert(std::is_same::value, "invalid string type"); + return reinterpret_cast(val); + } + FMT_CONSTEXPR const char* map(const unsigned char* val) { + static_assert(std::is_same::value, "invalid string type"); + return reinterpret_cast(val); + } + FMT_CONSTEXPR const char* map(signed char* val) { + const auto* const_val = val; + return map(const_val); + } + FMT_CONSTEXPR const char* map(unsigned char* val) { + const auto* const_val = val; + return map(const_val); + } + + FMT_CONSTEXPR const void* map(void* val) { return val; } + FMT_CONSTEXPR const void* map(const void* val) { return val; } + FMT_CONSTEXPR const void* map(std::nullptr_t val) { return val; } + template FMT_CONSTEXPR int map(const T*) { + // Formatting of arbitrary pointers is disallowed. If you want to output + // a pointer cast it to "void *" or "const void *". In particular, this + // forbids formatting of "[const] volatile char *" which is printed as bool + // by iostreams. + static_assert(!sizeof(T), "formatting of non-void pointers is disallowed"); + return 0; + } + + template ::value && + !has_formatter::value && + !has_fallback_formatter::value)> + FMT_CONSTEXPR auto map(const T& val) + -> decltype(std::declval().map( + static_cast::type>(val))) { + return map(static_cast::type>(val)); + } + template ::value && !is_char::value && + (has_formatter::value || + has_fallback_formatter::value))> + FMT_CONSTEXPR const T& map(const T& val) { + return val; + } + + template + FMT_CONSTEXPR auto map(const named_arg& val) + -> decltype(std::declval().map(val.value)) { + return map(val.value); + } + + unformattable map(...) { return {}; } +}; + +// A type constant after applying arg_mapper. +template +using mapped_type_constant = + type_constant().map(std::declval())), + typename Context::char_type>; + +enum { packed_arg_bits = 4 }; +// Maximum number of arguments with packed types. +enum { max_packed_args = 62 / packed_arg_bits }; +enum : unsigned long long { is_unpacked_bit = 1ULL << 63 }; +enum : unsigned long long { has_named_args_bit = 1ULL << 62 }; +} // namespace detail + +// A formatting argument. It is a trivially copyable/constructible type to +// allow storage in basic_memory_buffer. +template class basic_format_arg { + private: + detail::value value_; + detail::type type_; + + template + friend FMT_CONSTEXPR basic_format_arg detail::make_arg( + const T& value); + + template + friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis, + const basic_format_arg& arg) + -> decltype(vis(0)); + + friend class basic_format_args; + friend class dynamic_format_arg_store; + + using char_type = typename Context::char_type; + + template + friend struct detail::arg_data; + + basic_format_arg(const detail::named_arg_info* args, size_t size) + : value_(args, size) {} + + public: + class handle { + public: + explicit handle(detail::custom_value custom) : custom_(custom) {} + + void format(typename Context::parse_context_type& parse_ctx, + Context& ctx) const { + custom_.format(custom_.value, parse_ctx, ctx); + } + + private: + detail::custom_value custom_; + }; + + constexpr basic_format_arg() : type_(detail::type::none_type) {} + + constexpr explicit operator bool() const FMT_NOEXCEPT { + return type_ != detail::type::none_type; + } + + detail::type type() const { return type_; } + + bool is_integral() const { return detail::is_integral_type(type_); } + bool is_arithmetic() const { return detail::is_arithmetic_type(type_); } +}; + +/** + \rst + Visits an argument dispatching to the appropriate visit method based on + the argument type. For example, if the argument type is ``double`` then + ``vis(value)`` will be called with the value of type ``double``. + \endrst + */ +template +FMT_CONSTEXPR_DECL FMT_INLINE auto visit_format_arg( + Visitor&& vis, const basic_format_arg& arg) -> decltype(vis(0)) { + using char_type = typename Context::char_type; + switch (arg.type_) { + case detail::type::none_type: + break; + case detail::type::int_type: + return vis(arg.value_.int_value); + case detail::type::uint_type: + return vis(arg.value_.uint_value); + case detail::type::long_long_type: + return vis(arg.value_.long_long_value); + case detail::type::ulong_long_type: + return vis(arg.value_.ulong_long_value); +#if FMT_USE_INT128 + case detail::type::int128_type: + return vis(arg.value_.int128_value); + case detail::type::uint128_type: + return vis(arg.value_.uint128_value); +#else + case detail::type::int128_type: + case detail::type::uint128_type: + break; +#endif + case detail::type::bool_type: + return vis(arg.value_.bool_value); + case detail::type::char_type: + return vis(arg.value_.char_value); + case detail::type::float_type: + return vis(arg.value_.float_value); + case detail::type::double_type: + return vis(arg.value_.double_value); + case detail::type::long_double_type: + return vis(arg.value_.long_double_value); + case detail::type::cstring_type: + return vis(arg.value_.string.data); + case detail::type::string_type: + return vis(basic_string_view(arg.value_.string.data, + arg.value_.string.size)); + case detail::type::pointer_type: + return vis(arg.value_.pointer); + case detail::type::custom_type: + return vis(typename basic_format_arg::handle(arg.value_.custom)); + } + return vis(monostate()); +} + +template struct formattable : std::false_type {}; + +namespace detail { + +// A workaround for gcc 4.8 to make void_t work in a SFINAE context. +template struct void_t_impl { using type = void; }; + +template +using void_t = typename detail::void_t_impl::type; + +// Detect the iterator category of *any* given type in a SFINAE-friendly way. +// Unfortunately, older implementations of std::iterator_traits are not safe +// for use in a SFINAE-context. +template +struct iterator_category : std::false_type {}; + +template struct iterator_category { + using type = std::random_access_iterator_tag; +}; + +template +struct iterator_category> { + using type = typename It::iterator_category; +}; + +// Detect if *any* given type models the OutputIterator concept. +template class is_output_iterator { + // Check for mutability because all iterator categories derived from + // std::input_iterator_tag *may* also meet the requirements of an + // OutputIterator, thereby falling into the category of 'mutable iterators' + // [iterator.requirements.general] clause 4. The compiler reveals this + // property only at the point of *actually dereferencing* the iterator! + template + static decltype(*(std::declval())) test(std::input_iterator_tag); + template static char& test(std::output_iterator_tag); + template static const char& test(...); + + using type = decltype(test(typename iterator_category::type{})); + + public: + enum { value = !std::is_const>::value }; +}; + +template +struct is_back_insert_iterator : std::false_type {}; +template +struct is_back_insert_iterator> + : std::true_type {}; + +template +struct is_contiguous_back_insert_iterator : std::false_type {}; +template +struct is_contiguous_back_insert_iterator> + : is_contiguous {}; +template +struct is_contiguous_back_insert_iterator> + : std::true_type {}; + +// A type-erased reference to an std::locale to avoid heavy include. +class locale_ref { + private: + const void* locale_; // A type-erased pointer to std::locale. + + public: + locale_ref() : locale_(nullptr) {} + template explicit locale_ref(const Locale& loc); + + explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; } + + template Locale get() const; +}; + +template constexpr unsigned long long encode_types() { return 0; } + +template +constexpr unsigned long long encode_types() { + return static_cast(mapped_type_constant::value) | + (encode_types() << packed_arg_bits); +} + +template +FMT_CONSTEXPR basic_format_arg make_arg(const T& value) { + basic_format_arg arg; + arg.type_ = mapped_type_constant::value; + arg.value_ = arg_mapper().map(value); + return arg; +} + +template int check(unformattable) { + static_assert( + formattable(), + "Cannot format an argument. To make type T formattable provide a " + "formatter specialization: https://fmt.dev/dev/api.html#udt"); + return 0; +} +template inline const U& check(const U& val) { + return val; +} + +// The type template parameter is there to avoid an ODR violation when using +// a fallback formatter in one translation unit and an implicit conversion in +// another (not recommended). +template +inline value make_arg(const T& val) { + return check(arg_mapper().map(val)); +} + +template +inline basic_format_arg make_arg(const T& value) { + return make_arg(value); +} + +template struct is_reference_wrapper : std::false_type {}; +template +struct is_reference_wrapper> : std::true_type {}; + +template const T& unwrap(const T& v) { return v; } +template const T& unwrap(const std::reference_wrapper& v) { + return static_cast(v); +} + +class dynamic_arg_list { + // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for + // templates it doesn't complain about inability to deduce single translation + // unit for placing vtable. So storage_node_base is made a fake template. + template struct node { + virtual ~node() = default; + std::unique_ptr> next; + }; + + template struct typed_node : node<> { + T value; + + template + FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {} + + template + FMT_CONSTEXPR typed_node(const basic_string_view& arg) + : value(arg.data(), arg.size()) {} + }; + + std::unique_ptr> head_; + + public: + template const T& push(const Arg& arg) { + auto new_node = std::unique_ptr>(new typed_node(arg)); + auto& value = new_node->value; + new_node->next = std::move(head_); + head_ = std::move(new_node); + return value; + } +}; +} // namespace detail + +// Formatting context. +template class basic_format_context { + public: + /** The character type for the output. */ + using char_type = Char; + + private: + OutputIt out_; + basic_format_args args_; + detail::locale_ref loc_; + + public: + using iterator = OutputIt; + using format_arg = basic_format_arg; + using parse_context_type = basic_format_parse_context; + template using formatter_type = formatter; + + basic_format_context(const basic_format_context&) = delete; + void operator=(const basic_format_context&) = delete; + /** + Constructs a ``basic_format_context`` object. References to the arguments are + stored in the object so make sure they have appropriate lifetimes. + */ + basic_format_context(OutputIt out, + basic_format_args ctx_args, + detail::locale_ref loc = detail::locale_ref()) + : out_(out), args_(ctx_args), loc_(loc) {} + + format_arg arg(int id) const { return args_.get(id); } + format_arg arg(basic_string_view name) { return args_.get(name); } + int arg_id(basic_string_view name) { return args_.get_id(name); } + const basic_format_args& args() const { return args_; } + + detail::error_handler error_handler() { return {}; } + void on_error(const char* message) { error_handler().on_error(message); } + + // Returns an iterator to the beginning of the output range. + iterator out() { return out_; } + + // Advances the begin iterator to ``it``. + void advance_to(iterator it) { + if (!detail::is_back_insert_iterator()) out_ = it; + } + + detail::locale_ref locale() { return loc_; } +}; + +template +using buffer_context = + basic_format_context, Char>; +using format_context = buffer_context; +using wformat_context = buffer_context; + +// Workaround an alias issue: https://stackoverflow.com/q/62767544/471164. +#define FMT_BUFFER_CONTEXT(Char) \ + basic_format_context, Char> + +/** + \rst + An array of references to arguments. It can be implicitly converted into + `~fmt::basic_format_args` for passing into type-erased formatting functions + such as `~fmt::vformat`. + \endrst + */ +template +class format_arg_store +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + // Workaround a GCC template argument substitution bug. + : public basic_format_args +#endif +{ + private: + static const size_t num_args = sizeof...(Args); + static const size_t num_named_args = detail::count_named_args(); + static const bool is_packed = num_args <= detail::max_packed_args; + + using value_type = conditional_t, + basic_format_arg>; + + detail::arg_data + data_; + + friend class basic_format_args; + + static constexpr unsigned long long desc = + (is_packed ? detail::encode_types() + : detail::is_unpacked_bit | num_args) | + (num_named_args != 0 + ? static_cast(detail::has_named_args_bit) + : 0); + + public: + format_arg_store(const Args&... args) + : +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + basic_format_args(*this), +#endif + data_{detail::make_arg< + is_packed, Context, + detail::mapped_type_constant::value>(args)...} { + detail::init_named_args(data_.named_args(), 0, 0, args...); + } +}; + +/** + \rst + Constructs a `~fmt::format_arg_store` object that contains references to + arguments and can be implicitly converted to `~fmt::format_args`. `Context` + can be omitted in which case it defaults to `~fmt::context`. + See `~fmt::arg` for lifetime considerations. + \endrst + */ +template +inline format_arg_store make_format_args( + const Args&... args) { + return {args...}; +} + +/** + \rst + Constructs a `~fmt::format_arg_store` object that contains references + to arguments and can be implicitly converted to `~fmt::format_args`. + If ``format_str`` is a compile-time string then `make_args_checked` checks + its validity at compile time. + \endrst + */ +template > +inline auto make_args_checked(const S& format_str, + const remove_reference_t&... args) + -> format_arg_store, remove_reference_t...> { + static_assert( + detail::count<( + std::is_base_of>::value && + std::is_reference::value)...>() == 0, + "passing views as lvalues is disallowed"); + detail::check_format_string(format_str); + return {args...}; +} + +/** + \rst + Returns a named argument to be used in a formatting function. It should only + be used in a call to a formatting function. + + **Example**:: + + fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23)); + \endrst + */ +template +inline detail::named_arg arg(const Char* name, const T& arg) { + static_assert(!detail::is_named_arg(), "nested named arguments"); + return {name, arg}; +} + +/** + \rst + A dynamic version of `fmt::format_arg_store`. + It's equipped with a storage to potentially temporary objects which lifetimes + could be shorter than the format arguments object. + + It can be implicitly converted into `~fmt::basic_format_args` for passing + into type-erased formatting functions such as `~fmt::vformat`. + \endrst + */ +template +class dynamic_format_arg_store +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + // Workaround a GCC template argument substitution bug. + : public basic_format_args +#endif +{ + private: + using char_type = typename Context::char_type; + + template struct need_copy { + static constexpr detail::type mapped_type = + detail::mapped_type_constant::value; + + enum { + value = !(detail::is_reference_wrapper::value || + std::is_same>::value || + std::is_same>::value || + (mapped_type != detail::type::cstring_type && + mapped_type != detail::type::string_type && + mapped_type != detail::type::custom_type)) + }; + }; + + template + using stored_type = conditional_t::value, + std::basic_string, T>; + + // Storage of basic_format_arg must be contiguous. + std::vector> data_; + std::vector> named_info_; + + // Storage of arguments not fitting into basic_format_arg must grow + // without relocation because items in data_ refer to it. + detail::dynamic_arg_list dynamic_args_; + + friend class basic_format_args; + + unsigned long long get_types() const { + return detail::is_unpacked_bit | data_.size() | + (named_info_.empty() + ? 0ULL + : static_cast(detail::has_named_args_bit)); + } + + const basic_format_arg* data() const { + return named_info_.empty() ? data_.data() : data_.data() + 1; + } + + template void emplace_arg(const T& arg) { + data_.emplace_back(detail::make_arg(arg)); + } + + template + void emplace_arg(const detail::named_arg& arg) { + if (named_info_.empty()) { + constexpr const detail::named_arg_info* zero_ptr{nullptr}; + data_.insert(data_.begin(), {zero_ptr, 0}); + } + data_.emplace_back(detail::make_arg(detail::unwrap(arg.value))); + auto pop_one = [](std::vector>* data) { + data->pop_back(); + }; + std::unique_ptr>, decltype(pop_one)> + guard{&data_, pop_one}; + named_info_.push_back({arg.name, static_cast(data_.size() - 2u)}); + data_[0].value_.named_args = {named_info_.data(), named_info_.size()}; + guard.release(); + } + + public: + /** + \rst + Adds an argument into the dynamic store for later passing to a formatting + function. + + Note that custom types and string types (but not string views) are copied + into the store dynamically allocating memory if necessary. + + **Example**:: + + fmt::dynamic_format_arg_store store; + store.push_back(42); + store.push_back("abc"); + store.push_back(1.5f); + std::string result = fmt::vformat("{} and {} and {}", store); + \endrst + */ + template void push_back(const T& arg) { + if (detail::const_check(need_copy::value)) + emplace_arg(dynamic_args_.push>(arg)); + else + emplace_arg(detail::unwrap(arg)); + } + + /** + \rst + Adds a reference to the argument into the dynamic store for later passing to + a formatting function. Supports named arguments wrapped in + ``std::reference_wrapper`` via ``std::ref()``/``std::cref()``. + + **Example**:: + + fmt::dynamic_format_arg_store store; + char str[] = "1234567890"; + store.push_back(std::cref(str)); + int a1_val{42}; + auto a1 = fmt::arg("a1_", a1_val); + store.push_back(std::cref(a1)); + + // Changing str affects the output but only for string and custom types. + str[0] = 'X'; + + std::string result = fmt::vformat("{} and {a1_}"); + assert(result == "X234567890 and 42"); + \endrst + */ + template void push_back(std::reference_wrapper arg) { + static_assert( + detail::is_named_arg::type>::value || + need_copy::value, + "objects of built-in types and string views are always copied"); + emplace_arg(arg.get()); + } + + /** + Adds named argument into the dynamic store for later passing to a formatting + function. ``std::reference_wrapper`` is supported to avoid copying of the + argument. + */ + template + void push_back(const detail::named_arg& arg) { + const char_type* arg_name = + dynamic_args_.push>(arg.name).c_str(); + if (detail::const_check(need_copy::value)) { + emplace_arg( + fmt::arg(arg_name, dynamic_args_.push>(arg.value))); + } else { + emplace_arg(fmt::arg(arg_name, arg.value)); + } + } + + /** Erase all elements from the store */ + void clear() { + data_.clear(); + named_info_.clear(); + dynamic_args_ = detail::dynamic_arg_list(); + } + + /** + \rst + Reserves space to store at least *new_cap* arguments including + *new_cap_named* named arguments. + \endrst + */ + void reserve(size_t new_cap, size_t new_cap_named) { + FMT_ASSERT(new_cap >= new_cap_named, + "Set of arguments includes set of named arguments"); + data_.reserve(new_cap); + named_info_.reserve(new_cap_named); + } +}; + +/** + \rst + A view of a collection of formatting arguments. To avoid lifetime issues it + should only be used as a parameter type in type-erased functions such as + ``vformat``:: + + void vlog(string_view format_str, format_args args); // OK + format_args args = make_format_args(42); // Error: dangling reference + \endrst + */ +template class basic_format_args { + public: + using size_type = int; + using format_arg = basic_format_arg; + + private: + // A descriptor that contains information about formatting arguments. + // If the number of arguments is less or equal to max_packed_args then + // argument types are passed in the descriptor. This reduces binary code size + // per formatting function call. + unsigned long long desc_; + union { + // If is_packed() returns true then argument values are stored in values_; + // otherwise they are stored in args_. This is done to improve cache + // locality and reduce compiled code size since storing larger objects + // may require more code (at least on x86-64) even if the same amount of + // data is actually copied to stack. It saves ~10% on the bloat test. + const detail::value* values_; + const format_arg* args_; + }; + + bool is_packed() const { return (desc_ & detail::is_unpacked_bit) == 0; } + bool has_named_args() const { + return (desc_ & detail::has_named_args_bit) != 0; + } + + detail::type type(int index) const { + int shift = index * detail::packed_arg_bits; + unsigned int mask = (1 << detail::packed_arg_bits) - 1; + return static_cast((desc_ >> shift) & mask); + } + + basic_format_args(unsigned long long desc, + const detail::value* values) + : desc_(desc), values_(values) {} + basic_format_args(unsigned long long desc, const format_arg* args) + : desc_(desc), args_(args) {} + + public: + basic_format_args() : desc_(0) {} + + /** + \rst + Constructs a `basic_format_args` object from `~fmt::format_arg_store`. + \endrst + */ + template + FMT_INLINE basic_format_args(const format_arg_store& store) + : basic_format_args(store.desc, store.data_.args()) {} + + /** + \rst + Constructs a `basic_format_args` object from + `~fmt::dynamic_format_arg_store`. + \endrst + */ + FMT_INLINE basic_format_args(const dynamic_format_arg_store& store) + : basic_format_args(store.get_types(), store.data()) {} + + /** + \rst + Constructs a `basic_format_args` object from a dynamic set of arguments. + \endrst + */ + basic_format_args(const format_arg* args, int count) + : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count), + args) {} + + /** Returns the argument with the specified id. */ + format_arg get(int id) const { + format_arg arg; + if (!is_packed()) { + if (id < max_size()) arg = args_[id]; + return arg; + } + if (id >= detail::max_packed_args) return arg; + arg.type_ = type(id); + if (arg.type_ == detail::type::none_type) return arg; + arg.value_ = values_[id]; + return arg; + } + + template format_arg get(basic_string_view name) const { + int id = get_id(name); + return id >= 0 ? get(id) : format_arg(); + } + + template int get_id(basic_string_view name) const { + if (!has_named_args()) return -1; + const auto& named_args = + (is_packed() ? values_[-1] : args_[-1].value_).named_args; + for (size_t i = 0; i < named_args.size; ++i) { + if (named_args.data[i].name == name) return named_args.data[i].id; + } + return -1; + } + + int max_size() const { + unsigned long long max_packed = detail::max_packed_args; + return static_cast(is_packed() ? max_packed + : desc_ & ~detail::is_unpacked_bit); + } +}; + +/** An alias to ``basic_format_args``. */ +// It is a separate type rather than an alias to make symbols readable. +struct format_args : basic_format_args { + template + FMT_INLINE format_args(const Args&... args) : basic_format_args(args...) {} +}; +struct wformat_args : basic_format_args { + using basic_format_args::basic_format_args; +}; + +namespace detail { + +template ::value)> +std::basic_string vformat( + basic_string_view format_str, + basic_format_args>> args); + +FMT_API std::string vformat(string_view format_str, format_args args); + +template +buffer_appender vformat_to( + buffer& buf, basic_string_view format_str, + basic_format_args)> args); + +template ::value)> +inline void vprint_mojibake(std::FILE*, basic_string_view, const Args&) {} + +FMT_API void vprint_mojibake(std::FILE*, string_view, format_args); +#ifndef _WIN32 +inline void vprint_mojibake(std::FILE*, string_view, format_args) {} +#endif +} // namespace detail + +/** Formats a string and writes the output to ``out``. */ +// GCC 8 and earlier cannot handle std::back_insert_iterator with +// vformat_to(...) overload, so SFINAE on iterator type instead. +template , + FMT_ENABLE_IF(detail::is_output_iterator::value)> +OutputIt vformat_to( + OutputIt out, const S& format_str, + basic_format_args>> args) { + decltype(detail::get_buffer(out)) buf(detail::get_buffer_init(out)); + detail::vformat_to(buf, to_string_view(format_str), args); + return detail::get_iterator(buf); +} + +/** + \rst + Formats arguments, writes the result to the output iterator ``out`` and returns + the iterator past the end of the output range. + + **Example**:: + + std::vector out; + fmt::format_to(std::back_inserter(out), "{}", 42); + \endrst + */ +template ::value&& + detail::is_string::value)> +inline OutputIt format_to(OutputIt out, const S& format_str, Args&&... args) { + const auto& vargs = fmt::make_args_checked(format_str, args...); + return vformat_to(out, to_string_view(format_str), vargs); +} + +template struct format_to_n_result { + /** Iterator past the end of the output range. */ + OutputIt out; + /** Total (not truncated) output size. */ + size_t size; +}; + +template ::value)> +inline format_to_n_result vformat_to_n( + OutputIt out, size_t n, basic_string_view format_str, + basic_format_args>> args) { + detail::iterator_buffer buf(out, + n); + detail::vformat_to(buf, format_str, args); + return {buf.out(), buf.count()}; +} + +/** + \rst + Formats arguments, writes up to ``n`` characters of the result to the output + iterator ``out`` and returns the total output size and the iterator past the + end of the output range. + \endrst + */ +template ::value&& + detail::is_output_iterator::value)> +inline format_to_n_result format_to_n(OutputIt out, size_t n, + const S& format_str, + const Args&... args) { + const auto& vargs = fmt::make_args_checked(format_str, args...); + return vformat_to_n(out, n, to_string_view(format_str), vargs); +} + +/** + Returns the number of characters in the output of + ``format(format_str, args...)``. + */ +template +inline size_t formatted_size(string_view format_str, Args&&... args) { + const auto& vargs = fmt::make_args_checked(format_str, args...); + detail::counting_buffer<> buf; + detail::vformat_to(buf, format_str, vargs); + return buf.count(); +} + +template > +FMT_INLINE std::basic_string vformat( + const S& format_str, + basic_format_args>> args) { + return detail::vformat(to_string_view(format_str), args); +} + +/** + \rst + Formats arguments and returns the result as a string. + + **Example**:: + + #include + std::string message = fmt::format("The answer is {}", 42); + \endrst +*/ +// Pass char_t as a default template parameter instead of using +// std::basic_string> to reduce the symbol size. +template > +FMT_INLINE std::basic_string format(const S& format_str, Args&&... args) { + const auto& vargs = fmt::make_args_checked(format_str, args...); + return detail::vformat(to_string_view(format_str), vargs); +} + +FMT_API void vprint(string_view, format_args); +FMT_API void vprint(std::FILE*, string_view, format_args); + +/** + \rst + Formats ``args`` according to specifications in ``format_str`` and writes the + output to the file ``f``. Strings are assumed to be Unicode-encoded unless the + ``FMT_UNICODE`` macro is set to 0. + + **Example**:: + + fmt::print(stderr, "Don't {}!", "panic"); + \endrst + */ +template > +inline void print(std::FILE* f, const S& format_str, Args&&... args) { + const auto& vargs = fmt::make_args_checked(format_str, args...); + return detail::is_unicode() + ? vprint(f, to_string_view(format_str), vargs) + : detail::vprint_mojibake(f, to_string_view(format_str), vargs); +} + +/** + \rst + Formats ``args`` according to specifications in ``format_str`` and writes + the output to ``stdout``. Strings are assumed to be Unicode-encoded unless + the ``FMT_UNICODE`` macro is set to 0. + + **Example**:: + + fmt::print("Elapsed time: {0:.2f} seconds", 1.23); + \endrst + */ +template > +inline void print(const S& format_str, Args&&... args) { + const auto& vargs = fmt::make_args_checked(format_str, args...); + return detail::is_unicode() + ? vprint(to_string_view(format_str), vargs) + : detail::vprint_mojibake(stdout, to_string_view(format_str), + vargs); +} +FMT_END_NAMESPACE + +#endif // FMT_CORE_H_ diff --git a/src/3rdparty/fmt/format-inl.h b/src/3rdparty/fmt/format-inl.h new file mode 100644 index 00000000..b8249f33 --- /dev/null +++ b/src/3rdparty/fmt/format-inl.h @@ -0,0 +1,2801 @@ +// Formatting library for C++ - implementation +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_FORMAT_INL_H_ +#define FMT_FORMAT_INL_H_ + +#include +#include +#include +#include +#include +#include // std::memmove +#include +#include + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +# include +#endif + +#ifdef _WIN32 +# include // _isatty +#endif + +#include "format.h" + +// Dummy implementations of strerror_r and strerror_s called if corresponding +// system functions are not available. +inline fmt::detail::null<> strerror_r(int, char*, ...) { return {}; } +inline fmt::detail::null<> strerror_s(char*, size_t, ...) { return {}; } + +FMT_BEGIN_NAMESPACE +namespace detail { + +FMT_FUNC void assert_fail(const char* file, int line, const char* message) { + // Use unchecked std::fprintf to avoid triggering another assertion when + // writing to stderr fails + std::fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message); + // Chosen instead of std::abort to satisfy Clang in CUDA mode during device + // code pass. + std::terminate(); +} + +#ifndef _MSC_VER +# define FMT_SNPRINTF snprintf +#else // _MSC_VER +inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) { + va_list args; + va_start(args, format); + int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); + va_end(args); + return result; +} +# define FMT_SNPRINTF fmt_snprintf +#endif // _MSC_VER + +// A portable thread-safe version of strerror. +// Sets buffer to point to a string describing the error code. +// This can be either a pointer to a string stored in buffer, +// or a pointer to some static immutable string. +// Returns one of the following values: +// 0 - success +// ERANGE - buffer is not large enough to store the error message +// other - failure +// Buffer should be at least of size 1. +inline int safe_strerror(int error_code, char*& buffer, + size_t buffer_size) FMT_NOEXCEPT { + FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer"); + + class dispatcher { + private: + int error_code_; + char*& buffer_; + size_t buffer_size_; + + // A noop assignment operator to avoid bogus warnings. + void operator=(const dispatcher&) {} + + // Handle the result of XSI-compliant version of strerror_r. + int handle(int result) { + // glibc versions before 2.13 return result in errno. + return result == -1 ? errno : result; + } + + // Handle the result of GNU-specific version of strerror_r. + FMT_MAYBE_UNUSED + int handle(char* message) { + // If the buffer is full then the message is probably truncated. + if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1) + return ERANGE; + buffer_ = message; + return 0; + } + + // Handle the case when strerror_r is not available. + FMT_MAYBE_UNUSED + int handle(detail::null<>) { + return fallback(strerror_s(buffer_, buffer_size_, error_code_)); + } + + // Fallback to strerror_s when strerror_r is not available. + FMT_MAYBE_UNUSED + int fallback(int result) { + // If the buffer is full then the message is probably truncated. + return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE + : result; + } + +#if !FMT_MSC_VER + // Fallback to strerror if strerror_r and strerror_s are not available. + int fallback(detail::null<>) { + errno = 0; + buffer_ = strerror(error_code_); + return errno; + } +#endif + + public: + dispatcher(int err_code, char*& buf, size_t buf_size) + : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {} + + int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); } + }; + return dispatcher(error_code, buffer, buffer_size).run(); +} + +FMT_FUNC void format_error_code(detail::buffer& out, int error_code, + string_view message) FMT_NOEXCEPT { + // Report error code making sure that the output fits into + // inline_buffer_size to avoid dynamic memory allocation and potential + // bad_alloc. + out.try_resize(0); + static const char SEP[] = ": "; + static const char ERROR_STR[] = "error "; + // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. + size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; + auto abs_value = static_cast>(error_code); + if (detail::is_negative(error_code)) { + abs_value = 0 - abs_value; + ++error_code_size; + } + error_code_size += detail::to_unsigned(detail::count_digits(abs_value)); + auto it = buffer_appender(out); + if (message.size() <= inline_buffer_size - error_code_size) + format_to(it, "{}{}", message, SEP); + format_to(it, "{}{}", ERROR_STR, error_code); + assert(out.size() <= inline_buffer_size); +} + +FMT_FUNC void report_error(format_func func, int error_code, + string_view message) FMT_NOEXCEPT { + memory_buffer full_message; + func(full_message, error_code, message); + // Don't use fwrite_fully because the latter may throw. + (void)std::fwrite(full_message.data(), full_message.size(), 1, stderr); + std::fputc('\n', stderr); +} + +// A wrapper around fwrite that throws on error. +inline void fwrite_fully(const void* ptr, size_t size, size_t count, + FILE* stream) { + size_t written = std::fwrite(ptr, size, count, stream); + if (written < count) FMT_THROW(system_error(errno, "cannot write to file")); +} +} // namespace detail + +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) +namespace detail { + +template +locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { + static_assert(std::is_same::value, ""); +} + +template Locale locale_ref::get() const { + static_assert(std::is_same::value, ""); + return locale_ ? *static_cast(locale_) : std::locale(); +} + +template FMT_FUNC std::string grouping_impl(locale_ref loc) { + return std::use_facet>(loc.get()).grouping(); +} +template FMT_FUNC Char thousands_sep_impl(locale_ref loc) { + return std::use_facet>(loc.get()) + .thousands_sep(); +} +template FMT_FUNC Char decimal_point_impl(locale_ref loc) { + return std::use_facet>(loc.get()) + .decimal_point(); +} +} // namespace detail +#else +template +FMT_FUNC std::string detail::grouping_impl(locale_ref) { + return "\03"; +} +template FMT_FUNC Char detail::thousands_sep_impl(locale_ref) { + return FMT_STATIC_THOUSANDS_SEPARATOR; +} +template FMT_FUNC Char detail::decimal_point_impl(locale_ref) { + return '.'; +} +#endif + +FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT = default; +FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT = default; + +FMT_FUNC void system_error::init(int err_code, string_view format_str, + format_args args) { + error_code_ = err_code; + memory_buffer buffer; + format_system_error(buffer, err_code, vformat(format_str, args)); + std::runtime_error& base = *this; + base = std::runtime_error(to_string(buffer)); +} + +namespace detail { + +template <> FMT_FUNC int count_digits<4>(detail::fallback_uintptr n) { + // fallback_uintptr is always stored in little endian. + int i = static_cast(sizeof(void*)) - 1; + while (i > 0 && n.value[i] == 0) --i; + auto char_digits = std::numeric_limits::digits / 4; + return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1; +} + +template +const typename basic_data::digit_pair basic_data::digits[] = { + {'0', '0'}, {'0', '1'}, {'0', '2'}, {'0', '3'}, {'0', '4'}, {'0', '5'}, + {'0', '6'}, {'0', '7'}, {'0', '8'}, {'0', '9'}, {'1', '0'}, {'1', '1'}, + {'1', '2'}, {'1', '3'}, {'1', '4'}, {'1', '5'}, {'1', '6'}, {'1', '7'}, + {'1', '8'}, {'1', '9'}, {'2', '0'}, {'2', '1'}, {'2', '2'}, {'2', '3'}, + {'2', '4'}, {'2', '5'}, {'2', '6'}, {'2', '7'}, {'2', '8'}, {'2', '9'}, + {'3', '0'}, {'3', '1'}, {'3', '2'}, {'3', '3'}, {'3', '4'}, {'3', '5'}, + {'3', '6'}, {'3', '7'}, {'3', '8'}, {'3', '9'}, {'4', '0'}, {'4', '1'}, + {'4', '2'}, {'4', '3'}, {'4', '4'}, {'4', '5'}, {'4', '6'}, {'4', '7'}, + {'4', '8'}, {'4', '9'}, {'5', '0'}, {'5', '1'}, {'5', '2'}, {'5', '3'}, + {'5', '4'}, {'5', '5'}, {'5', '6'}, {'5', '7'}, {'5', '8'}, {'5', '9'}, + {'6', '0'}, {'6', '1'}, {'6', '2'}, {'6', '3'}, {'6', '4'}, {'6', '5'}, + {'6', '6'}, {'6', '7'}, {'6', '8'}, {'6', '9'}, {'7', '0'}, {'7', '1'}, + {'7', '2'}, {'7', '3'}, {'7', '4'}, {'7', '5'}, {'7', '6'}, {'7', '7'}, + {'7', '8'}, {'7', '9'}, {'8', '0'}, {'8', '1'}, {'8', '2'}, {'8', '3'}, + {'8', '4'}, {'8', '5'}, {'8', '6'}, {'8', '7'}, {'8', '8'}, {'8', '9'}, + {'9', '0'}, {'9', '1'}, {'9', '2'}, {'9', '3'}, {'9', '4'}, {'9', '5'}, + {'9', '6'}, {'9', '7'}, {'9', '8'}, {'9', '9'}}; + +template +const char basic_data::hex_digits[] = "0123456789abcdef"; + +#define FMT_POWERS_OF_10(factor) \ + factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \ + (factor)*1000000, (factor)*10000000, (factor)*100000000, \ + (factor)*1000000000 + +template +const uint64_t basic_data::powers_of_10_64[] = { + 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; + +template +const uint32_t basic_data::zero_or_powers_of_10_32[] = {0, 0, + FMT_POWERS_OF_10(1)}; + +template +const uint64_t basic_data::zero_or_powers_of_10_64[] = { + 0, 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; + +// Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340. +// These are generated by support/compute-powers.py. +template +const uint64_t basic_data::grisu_pow10_significands[] = { + 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76, + 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df, + 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c, + 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5, + 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57, + 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7, + 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e, + 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996, + 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126, + 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053, + 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f, + 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b, + 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06, + 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb, + 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000, + 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984, + 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068, + 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8, + 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758, + 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85, + 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d, + 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25, + 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2, + 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a, + 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410, + 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129, + 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85, + 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841, + 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b, +}; + +// Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding +// to significands above. +template +const int16_t basic_data::grisu_pow10_exponents[] = { + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, + -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, + -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, + -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, + -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, + 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, + 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, + 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066}; + +template +const divtest_table_entry basic_data::divtest_table_for_pow5_32[] = + {{0x00000001, 0xffffffff}, {0xcccccccd, 0x33333333}, + {0xc28f5c29, 0x0a3d70a3}, {0x26e978d5, 0x020c49ba}, + {0x3afb7e91, 0x0068db8b}, {0x0bcbe61d, 0x0014f8b5}, + {0x68c26139, 0x000431bd}, {0xae8d46a5, 0x0000d6bf}, + {0x22e90e21, 0x00002af3}, {0x3a2e9c6d, 0x00000897}, + {0x3ed61f49, 0x000001b7}}; + +template +const divtest_table_entry basic_data::divtest_table_for_pow5_64[] = + {{0x0000000000000001, 0xffffffffffffffff}, + {0xcccccccccccccccd, 0x3333333333333333}, + {0x8f5c28f5c28f5c29, 0x0a3d70a3d70a3d70}, + {0x1cac083126e978d5, 0x020c49ba5e353f7c}, + {0xd288ce703afb7e91, 0x0068db8bac710cb2}, + {0x5d4e8fb00bcbe61d, 0x0014f8b588e368f0}, + {0x790fb65668c26139, 0x000431bde82d7b63}, + {0xe5032477ae8d46a5, 0x0000d6bf94d5e57a}, + {0xc767074b22e90e21, 0x00002af31dc46118}, + {0x8e47ce423a2e9c6d, 0x0000089705f4136b}, + {0x4fa7f60d3ed61f49, 0x000001b7cdfd9d7b}, + {0x0fee64690c913975, 0x00000057f5ff85e5}, + {0x3662e0e1cf503eb1, 0x000000119799812d}, + {0xa47a2cf9f6433fbd, 0x0000000384b84d09}, + {0x54186f653140a659, 0x00000000b424dc35}, + {0x7738164770402145, 0x0000000024075f3d}, + {0xe4a4d1417cd9a041, 0x000000000734aca5}, + {0xc75429d9e5c5200d, 0x000000000170ef54}, + {0xc1773b91fac10669, 0x000000000049c977}, + {0x26b172506559ce15, 0x00000000000ec1e4}, + {0xd489e3a9addec2d1, 0x000000000002f394}, + {0x90e860bb892c8d5d, 0x000000000000971d}, + {0x502e79bf1b6f4f79, 0x0000000000001e39}, + {0xdcd618596be30fe5, 0x000000000000060b}}; + +template +const uint64_t basic_data::dragonbox_pow10_significands_64[] = { + 0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f, + 0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb, + 0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28, + 0xf1c90080baf72cb2, 0x971da05074da7bef, 0xbce5086492111aeb, + 0xec1e4a7db69561a6, 0x9392ee8e921d5d08, 0xb877aa3236a4b44a, + 0xe69594bec44de15c, 0x901d7cf73ab0acda, 0xb424dc35095cd810, + 0xe12e13424bb40e14, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff, + 0xdbe6fecebdedd5bf, 0x89705f4136b4a598, 0xabcc77118461cefd, + 0xd6bf94d5e57a42bd, 0x8637bd05af6c69b6, 0xa7c5ac471b478424, + 0xd1b71758e219652c, 0x83126e978d4fdf3c, 0xa3d70a3d70a3d70b, + 0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000, + 0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000, + 0xc350000000000000, 0xf424000000000000, 0x9896800000000000, + 0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000, + 0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000, + 0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000, + 0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000, + 0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000, + 0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0, + 0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940984, + 0xa18f07d736b90be5, 0xc9f2c9cd04674ede, 0xfc6f7c4045812296, + 0x9dc5ada82b70b59d, 0xc5371912364ce305, 0xf684df56c3e01bc6, + 0x9a130b963a6c115c, 0xc097ce7bc90715b3, 0xf0bdc21abb48db20, + 0x96769950b50d88f4, 0xbc143fa4e250eb31, 0xeb194f8e1ae525fd, + 0x92efd1b8d0cf37be, 0xb7abc627050305ad, 0xe596b7b0c643c719, + 0x8f7e32ce7bea5c6f, 0xb35dbf821ae4f38b, 0xe0352f62a19e306e}; + +template +const uint128_wrapper basic_data::dragonbox_pow10_significands_128[] = { +#if FMT_USE_FULL_CACHE_DRAGONBOX + {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, + {0x9faacf3df73609b1, 0x77b191618c54e9ad}, + {0xc795830d75038c1d, 0xd59df5b9ef6a2418}, + {0xf97ae3d0d2446f25, 0x4b0573286b44ad1e}, + {0x9becce62836ac577, 0x4ee367f9430aec33}, + {0xc2e801fb244576d5, 0x229c41f793cda740}, + {0xf3a20279ed56d48a, 0x6b43527578c11110}, + {0x9845418c345644d6, 0x830a13896b78aaaa}, + {0xbe5691ef416bd60c, 0x23cc986bc656d554}, + {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa9}, + {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6aa}, + {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc54}, + {0xe858ad248f5c22c9, 0xd1b3400f8f9cff69}, + {0x91376c36d99995be, 0x23100809b9c21fa2}, + {0xb58547448ffffb2d, 0xabd40a0c2832a78b}, + {0xe2e69915b3fff9f9, 0x16c90c8f323f516d}, + {0x8dd01fad907ffc3b, 0xae3da7d97f6792e4}, + {0xb1442798f49ffb4a, 0x99cd11cfdf41779d}, + {0xdd95317f31c7fa1d, 0x40405643d711d584}, + {0x8a7d3eef7f1cfc52, 0x482835ea666b2573}, + {0xad1c8eab5ee43b66, 0xda3243650005eed0}, + {0xd863b256369d4a40, 0x90bed43e40076a83}, + {0x873e4f75e2224e68, 0x5a7744a6e804a292}, + {0xa90de3535aaae202, 0x711515d0a205cb37}, + {0xd3515c2831559a83, 0x0d5a5b44ca873e04}, + {0x8412d9991ed58091, 0xe858790afe9486c3}, + {0xa5178fff668ae0b6, 0x626e974dbe39a873}, + {0xce5d73ff402d98e3, 0xfb0a3d212dc81290}, + {0x80fa687f881c7f8e, 0x7ce66634bc9d0b9a}, + {0xa139029f6a239f72, 0x1c1fffc1ebc44e81}, + {0xc987434744ac874e, 0xa327ffb266b56221}, + {0xfbe9141915d7a922, 0x4bf1ff9f0062baa9}, + {0x9d71ac8fada6c9b5, 0x6f773fc3603db4aa}, + {0xc4ce17b399107c22, 0xcb550fb4384d21d4}, + {0xf6019da07f549b2b, 0x7e2a53a146606a49}, + {0x99c102844f94e0fb, 0x2eda7444cbfc426e}, + {0xc0314325637a1939, 0xfa911155fefb5309}, + {0xf03d93eebc589f88, 0x793555ab7eba27cb}, + {0x96267c7535b763b5, 0x4bc1558b2f3458df}, + {0xbbb01b9283253ca2, 0x9eb1aaedfb016f17}, + {0xea9c227723ee8bcb, 0x465e15a979c1cadd}, + {0x92a1958a7675175f, 0x0bfacd89ec191eca}, + {0xb749faed14125d36, 0xcef980ec671f667c}, + {0xe51c79a85916f484, 0x82b7e12780e7401b}, + {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908811}, + {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa16}, + {0xdfbdcece67006ac9, 0x67a791e093e1d49b}, + {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e1}, + {0xaecc49914078536d, 0x58fae9f773886e19}, + {0xda7f5bf590966848, 0xaf39a475506a899f}, + {0x888f99797a5e012d, 0x6d8406c952429604}, + {0xaab37fd7d8f58178, 0xc8e5087ba6d33b84}, + {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a65}, + {0x855c3be0a17fcd26, 0x5cf2eea09a550680}, + {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f}, + {0xd0601d8efc57b08b, 0xf13b94daf124da27}, + {0x823c12795db6ce57, 0x76c53d08d6b70859}, + {0xa2cb1717b52481ed, 0x54768c4b0c64ca6f}, + {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd0a}, + {0xfe5d54150b090b02, 0xd3f93b35435d7c4d}, + {0x9efa548d26e5a6e1, 0xc47bc5014a1a6db0}, + {0xc6b8e9b0709f109a, 0x359ab6419ca1091c}, + {0xf867241c8cc6d4c0, 0xc30163d203c94b63}, + {0x9b407691d7fc44f8, 0x79e0de63425dcf1e}, + {0xc21094364dfb5636, 0x985915fc12f542e5}, + {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939e}, + {0x979cf3ca6cec5b5a, 0xa705992ceecf9c43}, + {0xbd8430bd08277231, 0x50c6ff782a838354}, + {0xece53cec4a314ebd, 0xa4f8bf5635246429}, + {0x940f4613ae5ed136, 0x871b7795e136be9a}, + {0xb913179899f68584, 0x28e2557b59846e40}, + {0xe757dd7ec07426e5, 0x331aeada2fe589d0}, + {0x9096ea6f3848984f, 0x3ff0d2c85def7622}, + {0xb4bca50b065abe63, 0x0fed077a756b53aa}, + {0xe1ebce4dc7f16dfb, 0xd3e8495912c62895}, + {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95d}, + {0xb080392cc4349dec, 0xbd8d794d96aacfb4}, + {0xdca04777f541c567, 0xecf0d7a0fc5583a1}, + {0x89e42caaf9491b60, 0xf41686c49db57245}, + {0xac5d37d5b79b6239, 0x311c2875c522ced6}, + {0xd77485cb25823ac7, 0x7d633293366b828c}, + {0x86a8d39ef77164bc, 0xae5dff9c02033198}, + {0xa8530886b54dbdeb, 0xd9f57f830283fdfd}, + {0xd267caa862a12d66, 0xd072df63c324fd7c}, + {0x8380dea93da4bc60, 0x4247cb9e59f71e6e}, + {0xa46116538d0deb78, 0x52d9be85f074e609}, + {0xcd795be870516656, 0x67902e276c921f8c}, + {0x806bd9714632dff6, 0x00ba1cd8a3db53b7}, + {0xa086cfcd97bf97f3, 0x80e8a40eccd228a5}, + {0xc8a883c0fdaf7df0, 0x6122cd128006b2ce}, + {0xfad2a4b13d1b5d6c, 0x796b805720085f82}, + {0x9cc3a6eec6311a63, 0xcbe3303674053bb1}, + {0xc3f490aa77bd60fc, 0xbedbfc4411068a9d}, + {0xf4f1b4d515acb93b, 0xee92fb5515482d45}, + {0x991711052d8bf3c5, 0x751bdd152d4d1c4b}, + {0xbf5cd54678eef0b6, 0xd262d45a78a0635e}, + {0xef340a98172aace4, 0x86fb897116c87c35}, + {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da1}, + {0xbae0a846d2195712, 0x8974836059cca10a}, + {0xe998d258869facd7, 0x2bd1a438703fc94c}, + {0x91ff83775423cc06, 0x7b6306a34627ddd0}, + {0xb67f6455292cbf08, 0x1a3bc84c17b1d543}, + {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a94}, + {0x8e938662882af53e, 0x547eb47b7282ee9d}, + {0xb23867fb2a35b28d, 0xe99e619a4f23aa44}, + {0xdec681f9f4c31f31, 0x6405fa00e2ec94d5}, + {0x8b3c113c38f9f37e, 0xde83bc408dd3dd05}, + {0xae0b158b4738705e, 0x9624ab50b148d446}, + {0xd98ddaee19068c76, 0x3badd624dd9b0958}, + {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d7}, + {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4d}, + {0xd47487cc8470652b, 0x7647c32000696720}, + {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e074}, + {0xa5fb0a17c777cf09, 0xf468107100525891}, + {0xcf79cc9db955c2cc, 0x7182148d4066eeb5}, + {0x81ac1fe293d599bf, 0xc6f14cd848405531}, + {0xa21727db38cb002f, 0xb8ada00e5a506a7d}, + {0xca9cf1d206fdc03b, 0xa6d90811f0e4851d}, + {0xfd442e4688bd304a, 0x908f4a166d1da664}, + {0x9e4a9cec15763e2e, 0x9a598e4e043287ff}, + {0xc5dd44271ad3cdba, 0x40eff1e1853f29fe}, + {0xf7549530e188c128, 0xd12bee59e68ef47d}, + {0x9a94dd3e8cf578b9, 0x82bb74f8301958cf}, + {0xc13a148e3032d6e7, 0xe36a52363c1faf02}, + {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac2}, + {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0ba}, + {0xbcb2b812db11a5de, 0x7415d448f6b6f0e8}, + {0xebdf661791d60f56, 0x111b495b3464ad22}, + {0x936b9fcebb25c995, 0xcab10dd900beec35}, + {0xb84687c269ef3bfb, 0x3d5d514f40eea743}, + {0xe65829b3046b0afa, 0x0cb4a5a3112a5113}, + {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ac}, + {0xb3f4e093db73a093, 0x59ed216765690f57}, + {0xe0f218b8d25088b8, 0x306869c13ec3532d}, + {0x8c974f7383725573, 0x1e414218c73a13fc}, + {0xafbd2350644eeacf, 0xe5d1929ef90898fb}, + {0xdbac6c247d62a583, 0xdf45f746b74abf3a}, + {0x894bc396ce5da772, 0x6b8bba8c328eb784}, + {0xab9eb47c81f5114f, 0x066ea92f3f326565}, + {0xd686619ba27255a2, 0xc80a537b0efefebe}, + {0x8613fd0145877585, 0xbd06742ce95f5f37}, + {0xa798fc4196e952e7, 0x2c48113823b73705}, + {0xd17f3b51fca3a7a0, 0xf75a15862ca504c6}, + {0x82ef85133de648c4, 0x9a984d73dbe722fc}, + {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebbb}, + {0xcc963fee10b7d1b3, 0x318df905079926a9}, + {0xffbbcfe994e5c61f, 0xfdf17746497f7053}, + {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa634}, + {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc1}, + {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b1}, + {0x9c1661a651213e2d, 0x06bea10ca65c084f}, + {0xc31bfa0fe5698db8, 0x486e494fcff30a63}, + {0xf3e2f893dec3f126, 0x5a89dba3c3efccfb}, + {0x986ddb5c6b3a76b7, 0xf89629465a75e01d}, + {0xbe89523386091465, 0xf6bbb397f1135824}, + {0xee2ba6c0678b597f, 0x746aa07ded582e2d}, + {0x94db483840b717ef, 0xa8c2a44eb4571cdd}, + {0xba121a4650e4ddeb, 0x92f34d62616ce414}, + {0xe896a0d7e51e1566, 0x77b020baf9c81d18}, + {0x915e2486ef32cd60, 0x0ace1474dc1d122f}, + {0xb5b5ada8aaff80b8, 0x0d819992132456bb}, + {0xe3231912d5bf60e6, 0x10e1fff697ed6c6a}, + {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2}, + {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb3}, + {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbdf}, + {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96c}, + {0xad4ab7112eb3929d, 0x86c16c98d2c953c7}, + {0xd89d64d57a607744, 0xe871c7bf077ba8b8}, + {0x87625f056c7c4a8b, 0x11471cd764ad4973}, + {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bd0}, + {0xd389b47879823479, 0x4aff1d108d4ec2c4}, + {0x843610cb4bf160cb, 0xcedf722a585139bb}, + {0xa54394fe1eedb8fe, 0xc2974eb4ee658829}, + {0xce947a3da6a9273e, 0x733d226229feea33}, + {0x811ccc668829b887, 0x0806357d5a3f5260}, + {0xa163ff802a3426a8, 0xca07c2dcb0cf26f8}, + {0xc9bcff6034c13052, 0xfc89b393dd02f0b6}, + {0xfc2c3f3841f17c67, 0xbbac2078d443ace3}, + {0x9d9ba7832936edc0, 0xd54b944b84aa4c0e}, + {0xc5029163f384a931, 0x0a9e795e65d4df12}, + {0xf64335bcf065d37d, 0x4d4617b5ff4a16d6}, + {0x99ea0196163fa42e, 0x504bced1bf8e4e46}, + {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d7}, + {0xf07da27a82c37088, 0x5d767327bb4e5a4d}, + {0x964e858c91ba2655, 0x3a6a07f8d510f870}, + {0xbbe226efb628afea, 0x890489f70a55368c}, + {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842f}, + {0x92c8ae6b464fc96f, 0x3b0b8bc90012929e}, + {0xb77ada0617e3bbcb, 0x09ce6ebb40173745}, + {0xe55990879ddcaabd, 0xcc420a6a101d0516}, + {0x8f57fa54c2a9eab6, 0x9fa946824a12232e}, + {0xb32df8e9f3546564, 0x47939822dc96abfa}, + {0xdff9772470297ebd, 0x59787e2b93bc56f8}, + {0x8bfbea76c619ef36, 0x57eb4edb3c55b65b}, + {0xaefae51477a06b03, 0xede622920b6b23f2}, + {0xdab99e59958885c4, 0xe95fab368e45ecee}, + {0x88b402f7fd75539b, 0x11dbcb0218ebb415}, + {0xaae103b5fcd2a881, 0xd652bdc29f26a11a}, + {0xd59944a37c0752a2, 0x4be76d3346f04960}, + {0x857fcae62d8493a5, 0x6f70a4400c562ddc}, + {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb953}, + {0xd097ad07a71f26b2, 0x7e2000a41346a7a8}, + {0x825ecc24c873782f, 0x8ed400668c0c28c9}, + {0xa2f67f2dfa90563b, 0x728900802f0f32fb}, + {0xcbb41ef979346bca, 0x4f2b40a03ad2ffba}, + {0xfea126b7d78186bc, 0xe2f610c84987bfa9}, + {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7ca}, + {0xc6ede63fa05d3143, 0x91503d1c79720dbc}, + {0xf8a95fcf88747d94, 0x75a44c6397ce912b}, + {0x9b69dbe1b548ce7c, 0xc986afbe3ee11abb}, + {0xc24452da229b021b, 0xfbe85badce996169}, + {0xf2d56790ab41c2a2, 0xfae27299423fb9c4}, + {0x97c560ba6b0919a5, 0xdccd879fc967d41b}, + {0xbdb6b8e905cb600f, 0x5400e987bbc1c921}, + {0xed246723473e3813, 0x290123e9aab23b69}, + {0x9436c0760c86e30b, 0xf9a0b6720aaf6522}, + {0xb94470938fa89bce, 0xf808e40e8d5b3e6a}, + {0xe7958cb87392c2c2, 0xb60b1d1230b20e05}, + {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c3}, + {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af4}, + {0xe2280b6c20dd5232, 0x25c6da63c38de1b1}, + {0x8d590723948a535f, 0x579c487e5a38ad0f}, + {0xb0af48ec79ace837, 0x2d835a9df0c6d852}, + {0xdcdb1b2798182244, 0xf8e431456cf88e66}, + {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b5900}, + {0xac8b2d36eed2dac5, 0xe272467e3d222f40}, + {0xd7adf884aa879177, 0x5b0ed81dcc6abb10}, + {0x86ccbb52ea94baea, 0x98e947129fc2b4ea}, + {0xa87fea27a539e9a5, 0x3f2398d747b36225}, + {0xd29fe4b18e88640e, 0x8eec7f0d19a03aae}, + {0x83a3eeeef9153e89, 0x1953cf68300424ad}, + {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd8}, + {0xcdb02555653131b6, 0x3792f412cb06794e}, + {0x808e17555f3ebf11, 0xe2bbd88bbee40bd1}, + {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec5}, + {0xc8de047564d20a8b, 0xf245825a5a445276}, + {0xfb158592be068d2e, 0xeed6e2f0f0d56713}, + {0x9ced737bb6c4183d, 0x55464dd69685606c}, + {0xc428d05aa4751e4c, 0xaa97e14c3c26b887}, + {0xf53304714d9265df, 0xd53dd99f4b3066a9}, + {0x993fe2c6d07b7fab, 0xe546a8038efe402a}, + {0xbf8fdb78849a5f96, 0xde98520472bdd034}, + {0xef73d256a5c0f77c, 0x963e66858f6d4441}, + {0x95a8637627989aad, 0xdde7001379a44aa9}, + {0xbb127c53b17ec159, 0x5560c018580d5d53}, + {0xe9d71b689dde71af, 0xaab8f01e6e10b4a7}, + {0x9226712162ab070d, 0xcab3961304ca70e9}, + {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d23}, + {0xe45c10c42a2b3b05, 0x8cb89a7db77c506b}, + {0x8eb98a7a9a5b04e3, 0x77f3608e92adb243}, + {0xb267ed1940f1c61c, 0x55f038b237591ed4}, + {0xdf01e85f912e37a3, 0x6b6c46dec52f6689}, + {0x8b61313bbabce2c6, 0x2323ac4b3b3da016}, + {0xae397d8aa96c1b77, 0xabec975e0a0d081b}, + {0xd9c7dced53c72255, 0x96e7bd358c904a22}, + {0x881cea14545c7575, 0x7e50d64177da2e55}, + {0xaa242499697392d2, 0xdde50bd1d5d0b9ea}, + {0xd4ad2dbfc3d07787, 0x955e4ec64b44e865}, + {0x84ec3c97da624ab4, 0xbd5af13bef0b113f}, + {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58f}, + {0xcfb11ead453994ba, 0x67de18eda5814af3}, + {0x81ceb32c4b43fcf4, 0x80eacf948770ced8}, + {0xa2425ff75e14fc31, 0xa1258379a94d028e}, + {0xcad2f7f5359a3b3e, 0x096ee45813a04331}, + {0xfd87b5f28300ca0d, 0x8bca9d6e188853fd}, + {0x9e74d1b791e07e48, 0x775ea264cf55347e}, + {0xc612062576589dda, 0x95364afe032a819e}, + {0xf79687aed3eec551, 0x3a83ddbd83f52205}, + {0x9abe14cd44753b52, 0xc4926a9672793543}, + {0xc16d9a0095928a27, 0x75b7053c0f178294}, + {0xf1c90080baf72cb1, 0x5324c68b12dd6339}, + {0x971da05074da7bee, 0xd3f6fc16ebca5e04}, + {0xbce5086492111aea, 0x88f4bb1ca6bcf585}, + {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6}, + {0x9392ee8e921d5d07, 0x3aff322e62439fd0}, + {0xb877aa3236a4b449, 0x09befeb9fad487c3}, + {0xe69594bec44de15b, 0x4c2ebe687989a9b4}, + {0x901d7cf73ab0acd9, 0x0f9d37014bf60a11}, + {0xb424dc35095cd80f, 0x538484c19ef38c95}, + {0xe12e13424bb40e13, 0x2865a5f206b06fba}, + {0x8cbccc096f5088cb, 0xf93f87b7442e45d4}, + {0xafebff0bcb24aafe, 0xf78f69a51539d749}, + {0xdbe6fecebdedd5be, 0xb573440e5a884d1c}, + {0x89705f4136b4a597, 0x31680a88f8953031}, + {0xabcc77118461cefc, 0xfdc20d2b36ba7c3e}, + {0xd6bf94d5e57a42bc, 0x3d32907604691b4d}, + {0x8637bd05af6c69b5, 0xa63f9a49c2c1b110}, + {0xa7c5ac471b478423, 0x0fcf80dc33721d54}, + {0xd1b71758e219652b, 0xd3c36113404ea4a9}, + {0x83126e978d4fdf3b, 0x645a1cac083126ea}, + {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4}, + {0xcccccccccccccccc, 0xcccccccccccccccd}, + {0x8000000000000000, 0x0000000000000000}, + {0xa000000000000000, 0x0000000000000000}, + {0xc800000000000000, 0x0000000000000000}, + {0xfa00000000000000, 0x0000000000000000}, + {0x9c40000000000000, 0x0000000000000000}, + {0xc350000000000000, 0x0000000000000000}, + {0xf424000000000000, 0x0000000000000000}, + {0x9896800000000000, 0x0000000000000000}, + {0xbebc200000000000, 0x0000000000000000}, + {0xee6b280000000000, 0x0000000000000000}, + {0x9502f90000000000, 0x0000000000000000}, + {0xba43b74000000000, 0x0000000000000000}, + {0xe8d4a51000000000, 0x0000000000000000}, + {0x9184e72a00000000, 0x0000000000000000}, + {0xb5e620f480000000, 0x0000000000000000}, + {0xe35fa931a0000000, 0x0000000000000000}, + {0x8e1bc9bf04000000, 0x0000000000000000}, + {0xb1a2bc2ec5000000, 0x0000000000000000}, + {0xde0b6b3a76400000, 0x0000000000000000}, + {0x8ac7230489e80000, 0x0000000000000000}, + {0xad78ebc5ac620000, 0x0000000000000000}, + {0xd8d726b7177a8000, 0x0000000000000000}, + {0x878678326eac9000, 0x0000000000000000}, + {0xa968163f0a57b400, 0x0000000000000000}, + {0xd3c21bcecceda100, 0x0000000000000000}, + {0x84595161401484a0, 0x0000000000000000}, + {0xa56fa5b99019a5c8, 0x0000000000000000}, + {0xcecb8f27f4200f3a, 0x0000000000000000}, + {0x813f3978f8940984, 0x4000000000000000}, + {0xa18f07d736b90be5, 0x5000000000000000}, + {0xc9f2c9cd04674ede, 0xa400000000000000}, + {0xfc6f7c4045812296, 0x4d00000000000000}, + {0x9dc5ada82b70b59d, 0xf020000000000000}, + {0xc5371912364ce305, 0x6c28000000000000}, + {0xf684df56c3e01bc6, 0xc732000000000000}, + {0x9a130b963a6c115c, 0x3c7f400000000000}, + {0xc097ce7bc90715b3, 0x4b9f100000000000}, + {0xf0bdc21abb48db20, 0x1e86d40000000000}, + {0x96769950b50d88f4, 0x1314448000000000}, + {0xbc143fa4e250eb31, 0x17d955a000000000}, + {0xeb194f8e1ae525fd, 0x5dcfab0800000000}, + {0x92efd1b8d0cf37be, 0x5aa1cae500000000}, + {0xb7abc627050305ad, 0xf14a3d9e40000000}, + {0xe596b7b0c643c719, 0x6d9ccd05d0000000}, + {0x8f7e32ce7bea5c6f, 0xe4820023a2000000}, + {0xb35dbf821ae4f38b, 0xdda2802c8a800000}, + {0xe0352f62a19e306e, 0xd50b2037ad200000}, + {0x8c213d9da502de45, 0x4526f422cc340000}, + {0xaf298d050e4395d6, 0x9670b12b7f410000}, + {0xdaf3f04651d47b4c, 0x3c0cdd765f114000}, + {0x88d8762bf324cd0f, 0xa5880a69fb6ac800}, + {0xab0e93b6efee0053, 0x8eea0d047a457a00}, + {0xd5d238a4abe98068, 0x72a4904598d6d880}, + {0x85a36366eb71f041, 0x47a6da2b7f864750}, + {0xa70c3c40a64e6c51, 0x999090b65f67d924}, + {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d}, + {0x82818f1281ed449f, 0xbff8f10e7a8921a4}, + {0xa321f2d7226895c7, 0xaff72d52192b6a0d}, + {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764490}, + {0xfee50b7025c36a08, 0x02f236d04753d5b4}, + {0x9f4f2726179a2245, 0x01d762422c946590}, + {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef5}, + {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb2}, + {0x9b934c3b330c8577, 0x63cc55f49f88eb2f}, + {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fb}, + {0xf316271c7fc3908a, 0x8bef464e3945ef7a}, + {0x97edd871cfda3a56, 0x97758bf0e3cbb5ac}, + {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea317}, + {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bdd}, + {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6a}, + {0xb975d6b6ee39e436, 0xb3e2fd538e122b44}, + {0xe7d34c64a9c85d44, 0x60dbbca87196b616}, + {0x90e40fbeea1d3a4a, 0xbc8955e946fe31cd}, + {0xb51d13aea4a488dd, 0x6babab6398bdbe41}, + {0xe264589a4dcdab14, 0xc696963c7eed2dd1}, + {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca2}, + {0xb0de65388cc8ada8, 0x3b25a55f43294bcb}, + {0xdd15fe86affad912, 0x49ef0eb713f39ebe}, + {0x8a2dbf142dfcc7ab, 0x6e3569326c784337}, + {0xacb92ed9397bf996, 0x49c2c37f07965404}, + {0xd7e77a8f87daf7fb, 0xdc33745ec97be906}, + {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a3}, + {0xa8acd7c0222311bc, 0xc40832ea0d68ce0c}, + {0xd2d80db02aabd62b, 0xf50a3fa490c30190}, + {0x83c7088e1aab65db, 0x792667c6da79e0fa}, + {0xa4b8cab1a1563f52, 0x577001b891185938}, + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86}, + {0x80b05e5ac60b6178, 0x544f8158315b05b4}, + {0xa0dc75f1778e39d6, 0x696361ae3db1c721}, + {0xc913936dd571c84c, 0x03bc3a19cd1e38e9}, + {0xfb5878494ace3a5f, 0x04ab48a04065c723}, + {0x9d174b2dcec0e47b, 0x62eb0d64283f9c76}, + {0xc45d1df942711d9a, 0x3ba5d0bd324f8394}, + {0xf5746577930d6500, 0xca8f44ec7ee36479}, + {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecb}, + {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67e}, + {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101e}, + {0x95d04aee3b80ece5, 0xbba1f1d158724a12}, + {0xbb445da9ca61281f, 0x2a8a6e45ae8edc97}, + {0xea1575143cf97226, 0xf52d09d71a3293bd}, + {0x924d692ca61be758, 0x593c2626705f9c56}, + {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836c}, + {0xe498f455c38b997a, 0x0b6dfb9c0f956447}, + {0x8edf98b59a373fec, 0x4724bd4189bd5eac}, + {0xb2977ee300c50fe7, 0x58edec91ec2cb657}, + {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ed}, + {0x8b865b215899f46c, 0xbd79e0d20082ee74}, + {0xae67f1e9aec07187, 0xecd8590680a3aa11}, + {0xda01ee641a708de9, 0xe80e6f4820cc9495}, + {0x884134fe908658b2, 0x3109058d147fdcdd}, + {0xaa51823e34a7eede, 0xbd4b46f0599fd415}, + {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91a}, + {0x850fadc09923329e, 0x03e2cf6bc604ddb0}, + {0xa6539930bf6bff45, 0x84db8346b786151c}, + {0xcfe87f7cef46ff16, 0xe612641865679a63}, + {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07e}, + {0xa26da3999aef7749, 0xe3be5e330f38f09d}, + {0xcb090c8001ab551c, 0x5cadf5bfd3072cc5}, + {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f6}, + {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afa}, + {0xc646d63501a1511d, 0xb281e1fd541501b8}, + {0xf7d88bc24209a565, 0x1f225a7ca91a4226}, + {0x9ae757596946075f, 0x3375788de9b06958}, + {0xc1a12d2fc3978937, 0x0052d6b1641c83ae}, + {0xf209787bb47d6b84, 0xc0678c5dbd23a49a}, + {0x9745eb4d50ce6332, 0xf840b7ba963646e0}, + {0xbd176620a501fbff, 0xb650e5a93bc3d898}, + {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebe}, + {0x93ba47c980e98cdf, 0xc66f336c36b10137}, + {0xb8a8d9bbe123f017, 0xb80b0047445d4184}, + {0xe6d3102ad96cec1d, 0xa60dc059157491e5}, + {0x9043ea1ac7e41392, 0x87c89837ad68db2f}, + {0xb454e4a179dd1877, 0x29babe4598c311fb}, + {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67a}, + {0x8ce2529e2734bb1d, 0x1899e4a65f58660c}, + {0xb01ae745b101e9e4, 0x5ec05dcff72e7f8f}, + {0xdc21a1171d42645d, 0x76707543f4fa1f73}, + {0x899504ae72497eba, 0x6a06494a791c53a8}, + {0xabfa45da0edbde69, 0x0487db9d17636892}, + {0xd6f8d7509292d603, 0x45a9d2845d3c42b6}, + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2}, + {0xa7f26836f282b732, 0x8e6cac7768d7141e}, + {0xd1ef0244af2364ff, 0x3207d795430cd926}, + {0x8335616aed761f1f, 0x7f44e6bd49e807b8}, + {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a6}, + {0xcd036837130890a1, 0x36dba887c37a8c0f}, + {0x802221226be55a64, 0xc2494954da2c9789}, + {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6c}, + {0xc83553c5c8965d3d, 0x6f92829494e5acc7}, + {0xfa42a8b73abbf48c, 0xcb772339ba1f17f9}, + {0x9c69a97284b578d7, 0xff2a760414536efb}, + {0xc38413cf25e2d70d, 0xfef5138519684aba}, + {0xf46518c2ef5b8cd1, 0x7eb258665fc25d69}, + {0x98bf2f79d5993802, 0xef2f773ffbd97a61}, + {0xbeeefb584aff8603, 0xaafb550ffacfd8fa}, + {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf38}, + {0x952ab45cfa97a0b2, 0xdd945a747bf26183}, + {0xba756174393d88df, 0x94f971119aeef9e4}, + {0xe912b9d1478ceb17, 0x7a37cd5601aab85d}, + {0x91abb422ccb812ee, 0xac62e055c10ab33a}, + {0xb616a12b7fe617aa, 0x577b986b314d6009}, + {0xe39c49765fdf9d94, 0xed5a7e85fda0b80b}, + {0x8e41ade9fbebc27d, 0x14588f13be847307}, + {0xb1d219647ae6b31c, 0x596eb2d8ae258fc8}, + {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bb}, + {0x8aec23d680043bee, 0x25de7bb9480d5854}, + {0xada72ccc20054ae9, 0xaf561aa79a10ae6a}, + {0xd910f7ff28069da4, 0x1b2ba1518094da04}, + {0x87aa9aff79042286, 0x90fb44d2f05d0842}, + {0xa99541bf57452b28, 0x353a1607ac744a53}, + {0xd3fa922f2d1675f2, 0x42889b8997915ce8}, + {0x847c9b5d7c2e09b7, 0x69956135febada11}, + {0xa59bc234db398c25, 0x43fab9837e699095}, + {0xcf02b2c21207ef2e, 0x94f967e45e03f4bb}, + {0x8161afb94b44f57d, 0x1d1be0eebac278f5}, + {0xa1ba1ba79e1632dc, 0x6462d92a69731732}, + {0xca28a291859bbf93, 0x7d7b8f7503cfdcfe}, + {0xfcb2cb35e702af78, 0x5cda735244c3d43e}, + {0x9defbf01b061adab, 0x3a0888136afa64a7}, + {0xc56baec21c7a1916, 0x088aaa1845b8fdd0}, + {0xf6c69a72a3989f5b, 0x8aad549e57273d45}, + {0x9a3c2087a63f6399, 0x36ac54e2f678864b}, + {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7dd}, + {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d5}, + {0x969eb7c47859e743, 0x9f644ae5a4b1b325}, + {0xbc4665b596706114, 0x873d5d9f0dde1fee}, + {0xeb57ff22fc0c7959, 0xa90cb506d155a7ea}, + {0x9316ff75dd87cbd8, 0x09a7f12442d588f2}, + {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb2f}, + {0xe5d3ef282a242e81, 0x8f1668c8a86da5fa}, + {0x8fa475791a569d10, 0xf96e017d694487bc}, + {0xb38d92d760ec4455, 0x37c981dcc395a9ac}, + {0xe070f78d3927556a, 0x85bbe253f47b1417}, + {0x8c469ab843b89562, 0x93956d7478ccec8e}, + {0xaf58416654a6babb, 0x387ac8d1970027b2}, + {0xdb2e51bfe9d0696a, 0x06997b05fcc0319e}, + {0x88fcf317f22241e2, 0x441fece3bdf81f03}, + {0xab3c2fddeeaad25a, 0xd527e81cad7626c3}, + {0xd60b3bd56a5586f1, 0x8a71e223d8d3b074}, + {0x85c7056562757456, 0xf6872d5667844e49}, + {0xa738c6bebb12d16c, 0xb428f8ac016561db}, + {0xd106f86e69d785c7, 0xe13336d701beba52}, + {0x82a45b450226b39c, 0xecc0024661173473}, + {0xa34d721642b06084, 0x27f002d7f95d0190}, + {0xcc20ce9bd35c78a5, 0x31ec038df7b441f4}, + {0xff290242c83396ce, 0x7e67047175a15271}, + {0x9f79a169bd203e41, 0x0f0062c6e984d386}, + {0xc75809c42c684dd1, 0x52c07b78a3e60868}, + {0xf92e0c3537826145, 0xa7709a56ccdf8a82}, + {0x9bbcc7a142b17ccb, 0x88a66076400bb691}, + {0xc2abf989935ddbfe, 0x6acff893d00ea435}, + {0xf356f7ebf83552fe, 0x0583f6b8c4124d43}, + {0x98165af37b2153de, 0xc3727a337a8b704a}, + {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5c}, + {0xeda2ee1c7064130c, 0x1162def06f79df73}, + {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba8}, + {0xb9a74a0637ce2ee1, 0x6d953e2bd7173692}, + {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0437}, + {0x910ab1d4db9914a0, 0x1d9c9892400a22a2}, + {0xb54d5e4a127f59c8, 0x2503beb6d00cab4b}, + {0xe2a0b5dc971f303a, 0x2e44ae64840fd61d}, + {0x8da471a9de737e24, 0x5ceaecfed289e5d2}, + {0xb10d8e1456105dad, 0x7425a83e872c5f47}, + {0xdd50f1996b947518, 0xd12f124e28f77719}, + {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa6f}, + {0xace73cbfdc0bfb7b, 0x636cc64d1001550b}, + {0xd8210befd30efa5a, 0x3c47f7e05401aa4e}, + {0x8714a775e3e95c78, 0x65acfaec34810a71}, + {0xa8d9d1535ce3b396, 0x7f1839a741a14d0d}, + {0xd31045a8341ca07c, 0x1ede48111209a050}, + {0x83ea2b892091e44d, 0x934aed0aab460432}, + {0xa4e4b66b68b65d60, 0xf81da84d5617853f}, + {0xce1de40642e3f4b9, 0x36251260ab9d668e}, + {0x80d2ae83e9ce78f3, 0xc1d72b7c6b426019}, + {0xa1075a24e4421730, 0xb24cf65b8612f81f}, + {0xc94930ae1d529cfc, 0xdee033f26797b627}, + {0xfb9b7cd9a4a7443c, 0x169840ef017da3b1}, + {0x9d412e0806e88aa5, 0x8e1f289560ee864e}, + {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e2}, + {0xf5b5d7ec8acb58a2, 0xae10af696774b1db}, + {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef29}, + {0xbff610b0cc6edd3f, 0x17fd090a58d32af3}, + {0xeff394dcff8a948e, 0xddfc4b4cef07f5b0}, + {0x95f83d0a1fb69cd9, 0x4abdaf101564f98e}, + {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f1}, + {0xea53df5fd18d5513, 0x84c86189216dc5ed}, + {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb4}, + {0xb7118682dbb66a77, 0x3fbc8c33221dc2a1}, + {0xe4d5e82392a40515, 0x0fabaf3feaa5334a}, + {0x8f05b1163ba6832d, 0x29cb4d87f2a7400e}, + {0xb2c71d5bca9023f8, 0x743e20e9ef511012}, + {0xdf78e4b2bd342cf6, 0x914da9246b255416}, + {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548e}, + {0xae9672aba3d0c320, 0xa184ac2473b529b1}, + {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741e}, + {0x8865899617fb1871, 0x7e2fa67c7a658892}, + {0xaa7eebfb9df9de8d, 0xddbb901b98feeab7}, + {0xd51ea6fa85785631, 0x552a74227f3ea565}, + {0x8533285c936b35de, 0xd53a88958f87275f}, + {0xa67ff273b8460356, 0x8a892abaf368f137}, + {0xd01fef10a657842c, 0x2d2b7569b0432d85}, + {0x8213f56a67f6b29b, 0x9c3b29620e29fc73}, + {0xa298f2c501f45f42, 0x8349f3ba91b47b8f}, + {0xcb3f2f7642717713, 0x241c70a936219a73}, + {0xfe0efb53d30dd4d7, 0xed238cd383aa0110}, + {0x9ec95d1463e8a506, 0xf4363804324a40aa}, + {0xc67bb4597ce2ce48, 0xb143c6053edcd0d5}, + {0xf81aa16fdc1b81da, 0xdd94b7868e94050a}, + {0x9b10a4e5e9913128, 0xca7cf2b4191c8326}, + {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f0}, + {0xf24a01a73cf2dccf, 0xbc633b39673c8cec}, + {0x976e41088617ca01, 0xd5be0503e085d813}, + {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e18}, + {0xec9c459d51852ba2, 0xddf8e7d60ed1219e}, + {0x93e1ab8252f33b45, 0xcabb90e5c942b503}, + {0xb8da1662e7b00a17, 0x3d6a751f3b936243}, + {0xe7109bfba19c0c9d, 0x0cc512670a783ad4}, + {0x906a617d450187e2, 0x27fb2b80668b24c5}, + {0xb484f9dc9641e9da, 0xb1f9f660802dedf6}, + {0xe1a63853bbd26451, 0x5e7873f8a0396973}, + {0x8d07e33455637eb2, 0xdb0b487b6423e1e8}, + {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda62}, + {0xdc5c5301c56b75f7, 0x7641a140cc7810fb}, + {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9d}, + {0xac2820d9623bf429, 0x546345fa9fbdcd44}, + {0xd732290fbacaf133, 0xa97c177947ad4095}, + {0x867f59a9d4bed6c0, 0x49ed8eabcccc485d}, + {0xa81f301449ee8c70, 0x5c68f256bfff5a74}, + {0xd226fc195c6a2f8c, 0x73832eec6fff3111}, + {0x83585d8fd9c25db7, 0xc831fd53c5ff7eab}, + {0xa42e74f3d032f525, 0xba3e7ca8b77f5e55}, + {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35eb}, + {0x80444b5e7aa7cf85, 0x7980d163cf5b81b3}, + {0xa0555e361951c366, 0xd7e105bcc332621f}, + {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa7}, + {0xfa856334878fc150, 0xb14f98f6f0feb951}, + {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d3}, + {0xc3b8358109e84f07, 0x0a862f80ec4700c8}, + {0xf4a642e14c6262c8, 0xcd27bb612758c0fa}, + {0x98e7e9cccfbd7dbd, 0x8038d51cb897789c}, + {0xbf21e44003acdd2c, 0xe0470a63e6bd56c3}, + {0xeeea5d5004981478, 0x1858ccfce06cac74}, + {0x95527a5202df0ccb, 0x0f37801e0c43ebc8}, + {0xbaa718e68396cffd, 0xd30560258f54e6ba}, + {0xe950df20247c83fd, 0x47c6b82ef32a2069}, + {0x91d28b7416cdd27e, 0x4cdc331d57fa5441}, + {0xb6472e511c81471d, 0xe0133fe4adf8e952}, + {0xe3d8f9e563a198e5, 0x58180fddd97723a6}, + {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7648}, + {0xb201833b35d63f73, 0x2cd2cc6551e513da}, + {0xde81e40a034bcf4f, 0xf8077f7ea65e58d1}, + {0x8b112e86420f6191, 0xfb04afaf27faf782}, + {0xadd57a27d29339f6, 0x79c5db9af1f9b563}, + {0xd94ad8b1c7380874, 0x18375281ae7822bc}, + {0x87cec76f1c830548, 0x8f2293910d0b15b5}, + {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb22}, + {0xd433179d9c8cb841, 0x5fa60692a46151eb}, + {0x849feec281d7f328, 0xdbc7c41ba6bcd333}, + {0xa5c7ea73224deff3, 0x12b9b522906c0800}, + {0xcf39e50feae16bef, 0xd768226b34870a00}, + {0x81842f29f2cce375, 0xe6a1158300d46640}, + {0xa1e53af46f801c53, 0x60495ae3c1097fd0}, + {0xca5e89b18b602368, 0x385bb19cb14bdfc4}, + {0xfcf62c1dee382c42, 0x46729e03dd9ed7b5}, + {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d1}, + {0xc5a05277621be293, 0xc7098b7305241885}, + {0xf70867153aa2db38, 0xb8cbee4fc66d1ea7} +#else + {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, + {0xce5d73ff402d98e3, 0xfb0a3d212dc81290}, + {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f}, + {0x86a8d39ef77164bc, 0xae5dff9c02033198}, + {0xd98ddaee19068c76, 0x3badd624dd9b0958}, + {0xafbd2350644eeacf, 0xe5d1929ef90898fb}, + {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2}, + {0xe55990879ddcaabd, 0xcc420a6a101d0516}, + {0xb94470938fa89bce, 0xf808e40e8d5b3e6a}, + {0x95a8637627989aad, 0xdde7001379a44aa9}, + {0xf1c90080baf72cb1, 0x5324c68b12dd6339}, + {0xc350000000000000, 0x0000000000000000}, + {0x9dc5ada82b70b59d, 0xf020000000000000}, + {0xfee50b7025c36a08, 0x02f236d04753d5b4}, + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86}, + {0xa6539930bf6bff45, 0x84db8346b786151c}, + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2}, + {0xd910f7ff28069da4, 0x1b2ba1518094da04}, + {0xaf58416654a6babb, 0x387ac8d1970027b2}, + {0x8da471a9de737e24, 0x5ceaecfed289e5d2}, + {0xe4d5e82392a40515, 0x0fabaf3feaa5334a}, + {0xb8da1662e7b00a17, 0x3d6a751f3b936243}, + {0x95527a5202df0ccb, 0x0f37801e0c43ebc8} +#endif +}; + +#if !FMT_USE_FULL_CACHE_DRAGONBOX +template +const uint64_t basic_data::powers_of_5_64[] = { + 0x0000000000000001, 0x0000000000000005, 0x0000000000000019, + 0x000000000000007d, 0x0000000000000271, 0x0000000000000c35, + 0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1, + 0x00000000001dcd65, 0x00000000009502f9, 0x0000000002e90edd, + 0x000000000e8d4a51, 0x0000000048c27395, 0x000000016bcc41e9, + 0x000000071afd498d, 0x0000002386f26fc1, 0x000000b1a2bc2ec5, + 0x000003782dace9d9, 0x00001158e460913d, 0x000056bc75e2d631, + 0x0001b1ae4d6e2ef5, 0x000878678326eac9, 0x002a5a058fc295ed, + 0x00d3c21bcecceda1, 0x0422ca8b0a00a425, 0x14adf4b7320334b9}; + +template +const uint32_t basic_data::dragonbox_pow10_recovery_errors[] = { + 0x50001400, 0x54044100, 0x54014555, 0x55954415, 0x54115555, 0x00000001, + 0x50000000, 0x00104000, 0x54010004, 0x05004001, 0x55555544, 0x41545555, + 0x54040551, 0x15445545, 0x51555514, 0x10000015, 0x00101100, 0x01100015, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04450514, 0x45414110, + 0x55555145, 0x50544050, 0x15040155, 0x11054140, 0x50111514, 0x11451454, + 0x00400541, 0x00000000, 0x55555450, 0x10056551, 0x10054011, 0x55551014, + 0x69514555, 0x05151109, 0x00155555}; +#endif + +template +const char basic_data::foreground_color[] = "\x1b[38;2;"; +template +const char basic_data::background_color[] = "\x1b[48;2;"; +template const char basic_data::reset_color[] = "\x1b[0m"; +template const wchar_t basic_data::wreset_color[] = L"\x1b[0m"; +template const char basic_data::signs[] = {0, '-', '+', ' '}; +template +const char basic_data::left_padding_shifts[] = {31, 31, 0, 1, 0}; +template +const char basic_data::right_padding_shifts[] = {0, 31, 0, 1, 0}; + +template struct bits { + static FMT_CONSTEXPR_DECL const int value = + static_cast(sizeof(T) * std::numeric_limits::digits); +}; + +class fp; +template fp normalize(fp value); + +// Lower (upper) boundary is a value half way between a floating-point value +// and its predecessor (successor). Boundaries have the same exponent as the +// value so only significands are stored. +struct boundaries { + uint64_t lower; + uint64_t upper; +}; + +// A handmade floating-point number f * pow(2, e). +class fp { + private: + using significand_type = uint64_t; + + template + using is_supported_float = bool_constant; + + public: + significand_type f; + int e; + + // All sizes are in bits. + // Subtract 1 to account for an implicit most significant bit in the + // normalized form. + static FMT_CONSTEXPR_DECL const int double_significand_size = + std::numeric_limits::digits - 1; + static FMT_CONSTEXPR_DECL const uint64_t implicit_bit = + 1ULL << double_significand_size; + static FMT_CONSTEXPR_DECL const int significand_size = + bits::value; + + fp() : f(0), e(0) {} + fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {} + + // Constructs fp from an IEEE754 double. It is a template to prevent compile + // errors on platforms where double is not IEEE754. + template explicit fp(Double d) { assign(d); } + + // Assigns d to this and return true iff predecessor is closer than successor. + template ::value)> + bool assign(Float d) { + // Assume float is in the format [sign][exponent][significand]. + using limits = std::numeric_limits; + const int float_significand_size = limits::digits - 1; + const int exponent_size = + bits::value - float_significand_size - 1; // -1 for sign + const uint64_t float_implicit_bit = 1ULL << float_significand_size; + const uint64_t significand_mask = float_implicit_bit - 1; + const uint64_t exponent_mask = (~0ULL >> 1) & ~significand_mask; + const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1; + constexpr bool is_double = sizeof(Float) == sizeof(uint64_t); + auto u = bit_cast>(d); + f = u & significand_mask; + int biased_e = + static_cast((u & exponent_mask) >> float_significand_size); + // Predecessor is closer if d is a normalized power of 2 (f == 0) other than + // the smallest normalized number (biased_e > 1). + bool is_predecessor_closer = f == 0 && biased_e > 1; + if (biased_e != 0) + f += float_implicit_bit; + else + biased_e = 1; // Subnormals use biased exponent 1 (min exponent). + e = biased_e - exponent_bias - float_significand_size; + return is_predecessor_closer; + } + + template ::value)> + bool assign(Float) { + *this = fp(); + return false; + } +}; + +// Normalizes the value converted from double and multiplied by (1 << SHIFT). +template fp normalize(fp value) { + // Handle subnormals. + const auto shifted_implicit_bit = fp::implicit_bit << SHIFT; + while ((value.f & shifted_implicit_bit) == 0) { + value.f <<= 1; + --value.e; + } + // Subtract 1 to account for hidden bit. + const auto offset = + fp::significand_size - fp::double_significand_size - SHIFT - 1; + value.f <<= offset; + value.e -= offset; + return value; +} + +inline bool operator==(fp x, fp y) { return x.f == y.f && x.e == y.e; } + +// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking. +inline uint64_t multiply(uint64_t lhs, uint64_t rhs) { +#if FMT_USE_INT128 + auto product = static_cast<__uint128_t>(lhs) * rhs; + auto f = static_cast(product >> 64); + return (static_cast(product) & (1ULL << 63)) != 0 ? f + 1 : f; +#else + // Multiply 32-bit parts of significands. + uint64_t mask = (1ULL << 32) - 1; + uint64_t a = lhs >> 32, b = lhs & mask; + uint64_t c = rhs >> 32, d = rhs & mask; + uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d; + // Compute mid 64-bit of result and round. + uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31); + return ac + (ad >> 32) + (bc >> 32) + (mid >> 32); +#endif +} + +inline fp operator*(fp x, fp y) { return {multiply(x.f, y.f), x.e + y.e + 64}; } + +// Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its +// (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`. +inline fp get_cached_power(int min_exponent, int& pow10_exponent) { + const int shift = 32; + const auto significand = static_cast(data::log10_2_significand); + int index = static_cast( + ((min_exponent + fp::significand_size - 1) * (significand >> shift) + + ((int64_t(1) << shift) - 1)) // ceil + >> 32 // arithmetic shift + ); + // Decimal exponent of the first (smallest) cached power of 10. + const int first_dec_exp = -348; + // Difference between 2 consecutive decimal exponents in cached powers of 10. + const int dec_exp_step = 8; + index = (index - first_dec_exp - 1) / dec_exp_step + 1; + pow10_exponent = first_dec_exp + index * dec_exp_step; + return {data::grisu_pow10_significands[index], + data::grisu_pow10_exponents[index]}; +} + +// A simple accumulator to hold the sums of terms in bigint::square if uint128_t +// is not available. +struct accumulator { + uint64_t lower; + uint64_t upper; + + accumulator() : lower(0), upper(0) {} + explicit operator uint32_t() const { return static_cast(lower); } + + void operator+=(uint64_t n) { + lower += n; + if (lower < n) ++upper; + } + void operator>>=(int shift) { + assert(shift == 32); + (void)shift; + lower = (upper << 32) | (lower >> 32); + upper >>= 32; + } +}; + +class bigint { + private: + // A bigint is stored as an array of bigits (big digits), with bigit at index + // 0 being the least significant one. + using bigit = uint32_t; + using double_bigit = uint64_t; + enum { bigits_capacity = 32 }; + basic_memory_buffer bigits_; + int exp_; + + bigit operator[](int index) const { return bigits_[to_unsigned(index)]; } + bigit& operator[](int index) { return bigits_[to_unsigned(index)]; } + + static FMT_CONSTEXPR_DECL const int bigit_bits = bits::value; + + friend struct formatter; + + void subtract_bigits(int index, bigit other, bigit& borrow) { + auto result = static_cast((*this)[index]) - other - borrow; + (*this)[index] = static_cast(result); + borrow = static_cast(result >> (bigit_bits * 2 - 1)); + } + + void remove_leading_zeros() { + int num_bigits = static_cast(bigits_.size()) - 1; + while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits; + bigits_.resize(to_unsigned(num_bigits + 1)); + } + + // Computes *this -= other assuming aligned bigints and *this >= other. + void subtract_aligned(const bigint& other) { + FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints"); + FMT_ASSERT(compare(*this, other) >= 0, ""); + bigit borrow = 0; + int i = other.exp_ - exp_; + for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j) + subtract_bigits(i, other.bigits_[j], borrow); + while (borrow > 0) subtract_bigits(i, 0, borrow); + remove_leading_zeros(); + } + + void multiply(uint32_t value) { + const double_bigit wide_value = value; + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * wide_value + carry; + bigits_[i] = static_cast(result); + carry = static_cast(result >> bigit_bits); + } + if (carry != 0) bigits_.push_back(carry); + } + + void multiply(uint64_t value) { + const bigit mask = ~bigit(0); + const double_bigit lower = value & mask; + const double_bigit upper = value >> bigit_bits; + double_bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * lower + (carry & mask); + carry = + bigits_[i] * upper + (result >> bigit_bits) + (carry >> bigit_bits); + bigits_[i] = static_cast(result); + } + while (carry != 0) { + bigits_.push_back(carry & mask); + carry >>= bigit_bits; + } + } + + public: + bigint() : exp_(0) {} + explicit bigint(uint64_t n) { assign(n); } + ~bigint() { assert(bigits_.capacity() <= bigits_capacity); } + + bigint(const bigint&) = delete; + void operator=(const bigint&) = delete; + + void assign(const bigint& other) { + auto size = other.bigits_.size(); + bigits_.resize(size); + auto data = other.bigits_.data(); + std::copy(data, data + size, make_checked(bigits_.data(), size)); + exp_ = other.exp_; + } + + void assign(uint64_t n) { + size_t num_bigits = 0; + do { + bigits_[num_bigits++] = n & ~bigit(0); + n >>= bigit_bits; + } while (n != 0); + bigits_.resize(num_bigits); + exp_ = 0; + } + + int num_bigits() const { return static_cast(bigits_.size()) + exp_; } + + FMT_NOINLINE bigint& operator<<=(int shift) { + assert(shift >= 0); + exp_ += shift / bigit_bits; + shift %= bigit_bits; + if (shift == 0) return *this; + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + bigit c = bigits_[i] >> (bigit_bits - shift); + bigits_[i] = (bigits_[i] << shift) + carry; + carry = c; + } + if (carry != 0) bigits_.push_back(carry); + return *this; + } + + template bigint& operator*=(Int value) { + FMT_ASSERT(value > 0, ""); + multiply(uint32_or_64_or_128_t(value)); + return *this; + } + + friend int compare(const bigint& lhs, const bigint& rhs) { + int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits(); + if (num_lhs_bigits != num_rhs_bigits) + return num_lhs_bigits > num_rhs_bigits ? 1 : -1; + int i = static_cast(lhs.bigits_.size()) - 1; + int j = static_cast(rhs.bigits_.size()) - 1; + int end = i - j; + if (end < 0) end = 0; + for (; i >= end; --i, --j) { + bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j]; + if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1; + } + if (i != j) return i > j ? 1 : -1; + return 0; + } + + // Returns compare(lhs1 + lhs2, rhs). + friend int add_compare(const bigint& lhs1, const bigint& lhs2, + const bigint& rhs) { + int max_lhs_bigits = (std::max)(lhs1.num_bigits(), lhs2.num_bigits()); + int num_rhs_bigits = rhs.num_bigits(); + if (max_lhs_bigits + 1 < num_rhs_bigits) return -1; + if (max_lhs_bigits > num_rhs_bigits) return 1; + auto get_bigit = [](const bigint& n, int i) -> bigit { + return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0; + }; + double_bigit borrow = 0; + int min_exp = (std::min)((std::min)(lhs1.exp_, lhs2.exp_), rhs.exp_); + for (int i = num_rhs_bigits - 1; i >= min_exp; --i) { + double_bigit sum = + static_cast(get_bigit(lhs1, i)) + get_bigit(lhs2, i); + bigit rhs_bigit = get_bigit(rhs, i); + if (sum > rhs_bigit + borrow) return 1; + borrow = rhs_bigit + borrow - sum; + if (borrow > 1) return -1; + borrow <<= bigit_bits; + } + return borrow != 0 ? -1 : 0; + } + + // Assigns pow(10, exp) to this bigint. + void assign_pow10(int exp) { + assert(exp >= 0); + if (exp == 0) return assign(1); + // Find the top bit. + int bitmask = 1; + while (exp >= bitmask) bitmask <<= 1; + bitmask >>= 1; + // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by + // repeated squaring and multiplication. + assign(5); + bitmask >>= 1; + while (bitmask != 0) { + square(); + if ((exp & bitmask) != 0) *this *= 5; + bitmask >>= 1; + } + *this <<= exp; // Multiply by pow(2, exp) by shifting. + } + + void square() { + basic_memory_buffer n(std::move(bigits_)); + int num_bigits = static_cast(bigits_.size()); + int num_result_bigits = 2 * num_bigits; + bigits_.resize(to_unsigned(num_result_bigits)); + using accumulator_t = conditional_t; + auto sum = accumulator_t(); + for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) { + // Compute bigit at position bigit_index of the result by adding + // cross-product terms n[i] * n[j] such that i + j == bigit_index. + for (int i = 0, j = bigit_index; j >= 0; ++i, --j) { + // Most terms are multiplied twice which can be optimized in the future. + sum += static_cast(n[i]) * n[j]; + } + (*this)[bigit_index] = static_cast(sum); + sum >>= bits::value; // Compute the carry. + } + // Do the same for the top half. + for (int bigit_index = num_bigits; bigit_index < num_result_bigits; + ++bigit_index) { + for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;) + sum += static_cast(n[i++]) * n[j--]; + (*this)[bigit_index] = static_cast(sum); + sum >>= bits::value; + } + --num_result_bigits; + remove_leading_zeros(); + exp_ *= 2; + } + + // If this bigint has a bigger exponent than other, adds trailing zero to make + // exponents equal. This simplifies some operations such as subtraction. + void align(const bigint& other) { + int exp_difference = exp_ - other.exp_; + if (exp_difference <= 0) return; + int num_bigits = static_cast(bigits_.size()); + bigits_.resize(to_unsigned(num_bigits + exp_difference)); + for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j) + bigits_[j] = bigits_[i]; + std::uninitialized_fill_n(bigits_.data(), exp_difference, 0); + exp_ -= exp_difference; + } + + // Divides this bignum by divisor, assigning the remainder to this and + // returning the quotient. + int divmod_assign(const bigint& divisor) { + FMT_ASSERT(this != &divisor, ""); + if (compare(*this, divisor) < 0) return 0; + FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, ""); + align(divisor); + int quotient = 0; + do { + subtract_aligned(divisor); + ++quotient; + } while (compare(*this, divisor) >= 0); + return quotient; + } +}; + +enum class round_direction { unknown, up, down }; + +// Given the divisor (normally a power of 10), the remainder = v % divisor for +// some number v and the error, returns whether v should be rounded up, down, or +// whether the rounding direction can't be determined due to error. +// error should be less than divisor / 2. +inline round_direction get_round_direction(uint64_t divisor, uint64_t remainder, + uint64_t error) { + FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow. + FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow. + FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow. + // Round down if (remainder + error) * 2 <= divisor. + if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2) + return round_direction::down; + // Round up if (remainder - error) * 2 >= divisor. + if (remainder >= error && + remainder - error >= divisor - (remainder - error)) { + return round_direction::up; + } + return round_direction::unknown; +} + +namespace digits { +enum result { + more, // Generate more digits. + done, // Done generating digits. + error // Digit generation cancelled due to an error. +}; +} + +// Generates output using the Grisu digit-gen algorithm. +// error: the size of the region (lower, upper) outside of which numbers +// definitely do not round to value (Delta in Grisu3). +template +FMT_ALWAYS_INLINE digits::result grisu_gen_digits(fp value, uint64_t error, + int& exp, Handler& handler) { + const fp one(1ULL << -value.e, value.e); + // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be + // zero because it contains a product of two 64-bit numbers with MSB set (due + // to normalization) - 1, shifted right by at most 60 bits. + auto integral = static_cast(value.f >> -one.e); + FMT_ASSERT(integral != 0, ""); + FMT_ASSERT(integral == value.f >> -one.e, ""); + // The fractional part of scaled value (p2 in Grisu) c = value % one. + uint64_t fractional = value.f & (one.f - 1); + exp = count_digits(integral); // kappa in Grisu. + // Divide by 10 to prevent overflow. + auto result = handler.on_start(data::powers_of_10_64[exp - 1] << -one.e, + value.f / 10, error * 10, exp); + if (result != digits::more) return result; + // Generate digits for the integral part. This can produce up to 10 digits. + do { + uint32_t digit = 0; + auto divmod_integral = [&](uint32_t divisor) { + digit = integral / divisor; + integral %= divisor; + }; + // This optimization by Milo Yip reduces the number of integer divisions by + // one per iteration. + switch (exp) { + case 10: + divmod_integral(1000000000); + break; + case 9: + divmod_integral(100000000); + break; + case 8: + divmod_integral(10000000); + break; + case 7: + divmod_integral(1000000); + break; + case 6: + divmod_integral(100000); + break; + case 5: + divmod_integral(10000); + break; + case 4: + divmod_integral(1000); + break; + case 3: + divmod_integral(100); + break; + case 2: + divmod_integral(10); + break; + case 1: + digit = integral; + integral = 0; + break; + default: + FMT_ASSERT(false, "invalid number of digits"); + } + --exp; + auto remainder = (static_cast(integral) << -one.e) + fractional; + result = handler.on_digit(static_cast('0' + digit), + data::powers_of_10_64[exp] << -one.e, remainder, + error, exp, true); + if (result != digits::more) return result; + } while (exp > 0); + // Generate digits for the fractional part. + for (;;) { + fractional *= 10; + error *= 10; + char digit = static_cast('0' + (fractional >> -one.e)); + fractional &= one.f - 1; + --exp; + result = handler.on_digit(digit, one.f, fractional, error, exp, false); + if (result != digits::more) return result; + } +} + +// The fixed precision digit handler. +struct fixed_handler { + char* buf; + int size; + int precision; + int exp10; + bool fixed; + + digits::result on_start(uint64_t divisor, uint64_t remainder, uint64_t error, + int& exp) { + // Non-fixed formats require at least one digit and no precision adjustment. + if (!fixed) return digits::more; + // Adjust fixed precision by exponent because it is relative to decimal + // point. + precision += exp + exp10; + // Check if precision is satisfied just by leading zeros, e.g. + // format("{:.2f}", 0.001) gives "0.00" without generating any digits. + if (precision > 0) return digits::more; + if (precision < 0) return digits::done; + auto dir = get_round_direction(divisor, remainder, error); + if (dir == round_direction::unknown) return digits::error; + buf[size++] = dir == round_direction::up ? '1' : '0'; + return digits::done; + } + + digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder, + uint64_t error, int, bool integral) { + FMT_ASSERT(remainder < divisor, ""); + buf[size++] = digit; + if (!integral && error >= remainder) return digits::error; + if (size < precision) return digits::more; + if (!integral) { + // Check if error * 2 < divisor with overflow prevention. + // The check is not needed for the integral part because error = 1 + // and divisor > (1 << 32) there. + if (error >= divisor || error >= divisor - error) return digits::error; + } else { + FMT_ASSERT(error == 1 && divisor > 2, ""); + } + auto dir = get_round_direction(divisor, remainder, error); + if (dir != round_direction::up) + return dir == round_direction::down ? digits::done : digits::error; + ++buf[size - 1]; + for (int i = size - 1; i > 0 && buf[i] > '9'; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] > '9') { + buf[0] = '1'; + if (fixed) buf[size++] = '0'; + else ++exp10; + } + return digits::done; + } +}; + +// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox. +namespace dragonbox { +// Computes 128-bit result of multiplication of two 64-bit unsigned integers. +FMT_SAFEBUFFERS inline uint128_wrapper umul128(uint64_t x, + uint64_t y) FMT_NOEXCEPT { +#if FMT_USE_INT128 + return static_cast(x) * static_cast(y); +#elif defined(_MSC_VER) && defined(_M_X64) + uint128_wrapper result; + result.low_ = _umul128(x, y, &result.high_); + return result; +#else + const uint64_t mask = (uint64_t(1) << 32) - uint64_t(1); + + uint64_t a = x >> 32; + uint64_t b = x & mask; + uint64_t c = y >> 32; + uint64_t d = y & mask; + + uint64_t ac = a * c; + uint64_t bc = b * c; + uint64_t ad = a * d; + uint64_t bd = b * d; + + uint64_t intermediate = (bd >> 32) + (ad & mask) + (bc & mask); + + return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32), + (intermediate << 32) + (bd & mask)}; +#endif +} + +// Computes upper 64 bits of multiplication of two 64-bit unsigned integers. +FMT_SAFEBUFFERS inline uint64_t umul128_upper64(uint64_t x, + uint64_t y) FMT_NOEXCEPT { +#if FMT_USE_INT128 + auto p = static_cast(x) * static_cast(y); + return static_cast(p >> 64); +#elif defined(_MSC_VER) && defined(_M_X64) + return __umulh(x, y); +#else + return umul128(x, y).high(); +#endif +} + +// Computes upper 64 bits of multiplication of a 64-bit unsigned integer and a +// 128-bit unsigned integer. +FMT_SAFEBUFFERS inline uint64_t umul192_upper64(uint64_t x, uint128_wrapper y) + FMT_NOEXCEPT { + uint128_wrapper g0 = umul128(x, y.high()); + g0 += umul128_upper64(x, y.low()); + return g0.high(); +} + +// Computes upper 32 bits of multiplication of a 32-bit unsigned integer and a +// 64-bit unsigned integer. +inline uint32_t umul96_upper32(uint32_t x, uint64_t y) FMT_NOEXCEPT { + return static_cast(umul128_upper64(x, y)); +} + +// Computes middle 64 bits of multiplication of a 64-bit unsigned integer and a +// 128-bit unsigned integer. +FMT_SAFEBUFFERS inline uint64_t umul192_middle64(uint64_t x, uint128_wrapper y) + FMT_NOEXCEPT { + uint64_t g01 = x * y.high(); + uint64_t g10 = umul128_upper64(x, y.low()); + return g01 + g10; +} + +// Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a +// 64-bit unsigned integer. +inline uint64_t umul96_lower64(uint32_t x, uint64_t y) FMT_NOEXCEPT { + return x * y; +} + +// Computes floor(log10(pow(2, e))) for e in [-1700, 1700] using the method from +// https://fmt.dev/papers/Grisu-Exact.pdf#page=5, section 3.4. +inline int floor_log10_pow2(int e) FMT_NOEXCEPT { + FMT_ASSERT(e <= 1700 && e >= -1700, "too large exponent"); + const int shift = 22; + return (e * static_cast(data::log10_2_significand >> (64 - shift))) >> + shift; +} + +// Various fast log computations. +inline int floor_log2_pow10(int e) FMT_NOEXCEPT { + FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent"); + const uint64_t log2_10_integer_part = 3; + const uint64_t log2_10_fractional_digits = 0x5269e12f346e2bf9; + const int shift_amount = 19; + return (e * static_cast( + (log2_10_integer_part << shift_amount) | + (log2_10_fractional_digits >> (64 - shift_amount)))) >> + shift_amount; +} +inline int floor_log10_pow2_minus_log10_4_over_3(int e) FMT_NOEXCEPT { + FMT_ASSERT(e <= 1700 && e >= -1700, "too large exponent"); + const uint64_t log10_4_over_3_fractional_digits = 0x1ffbfc2bbc780375; + const int shift_amount = 22; + return (e * static_cast(data::log10_2_significand >> + (64 - shift_amount)) - + static_cast(log10_4_over_3_fractional_digits >> + (64 - shift_amount))) >> + shift_amount; +} + +// Returns true iff x is divisible by pow(2, exp). +inline bool divisible_by_power_of_2(uint32_t x, int exp) FMT_NOEXCEPT { + FMT_ASSERT(exp >= 1, ""); + FMT_ASSERT(x != 0, ""); +#ifdef FMT_BUILTIN_CTZ + return FMT_BUILTIN_CTZ(x) >= exp; +#else + return exp < num_bits() && x == ((x >> exp) << exp); +#endif +} +inline bool divisible_by_power_of_2(uint64_t x, int exp) FMT_NOEXCEPT { + FMT_ASSERT(exp >= 1, ""); + FMT_ASSERT(x != 0, ""); +#ifdef FMT_BUILTIN_CTZLL + return FMT_BUILTIN_CTZLL(x) >= exp; +#else + return (exp < num_bits()) && x == ((x >> exp) << exp); +#endif +} + +// Returns true iff x is divisible by pow(5, exp). +inline bool divisible_by_power_of_5(uint32_t x, int exp) FMT_NOEXCEPT { + FMT_ASSERT(exp <= 10, "too large exponent"); + return x * data::divtest_table_for_pow5_32[exp].mod_inv <= + data::divtest_table_for_pow5_32[exp].max_quotient; +} +inline bool divisible_by_power_of_5(uint64_t x, int exp) FMT_NOEXCEPT { + FMT_ASSERT(exp <= 23, "too large exponent"); + return x * data::divtest_table_for_pow5_64[exp].mod_inv <= + data::divtest_table_for_pow5_64[exp].max_quotient; +} + +// Replaces n by floor(n / pow(5, N)) returning true if and only if n is +// divisible by pow(5, N). +// Precondition: n <= 2 * pow(5, N + 1). +template +bool check_divisibility_and_divide_by_pow5(uint32_t& n) FMT_NOEXCEPT { + static constexpr struct { + uint32_t magic_number; + int bits_for_comparison; + uint32_t threshold; + int shift_amount; + } infos[] = {{0xcccd, 16, 0x3333, 18}, {0xa429, 8, 0x0a, 20}}; + constexpr auto info = infos[N - 1]; + n *= info.magic_number; + const uint32_t comparison_mask = (1u << info.bits_for_comparison) - 1; + bool result = (n & comparison_mask) <= info.threshold; + n >>= info.shift_amount; + return result; +} + +// Computes floor(n / pow(10, N)) for small n and N. +// Precondition: n <= pow(10, N + 1). +template uint32_t small_division_by_pow10(uint32_t n) FMT_NOEXCEPT { + static constexpr struct { + uint32_t magic_number; + int shift_amount; + uint32_t divisor_times_10; + } infos[] = {{0xcccd, 19, 100}, {0xa3d8, 22, 1000}}; + constexpr auto info = infos[N - 1]; + FMT_ASSERT(n <= info.divisor_times_10, "n is too large"); + return n * info.magic_number >> info.shift_amount; +} + +// Computes floor(n / 10^(kappa + 1)) (float) +inline uint32_t divide_by_10_to_kappa_plus_1(uint32_t n) FMT_NOEXCEPT { + return n / float_info::big_divisor; +} +// Computes floor(n / 10^(kappa + 1)) (double) +inline uint64_t divide_by_10_to_kappa_plus_1(uint64_t n) FMT_NOEXCEPT { + return umul128_upper64(n, 0x83126e978d4fdf3c) >> 9; +} + +// Various subroutines using pow10 cache +template struct cache_accessor; + +template <> struct cache_accessor { + using carrier_uint = float_info::carrier_uint; + using cache_entry_type = uint64_t; + + static uint64_t get_cached_power(int k) FMT_NOEXCEPT { + FMT_ASSERT(k >= float_info::min_k && k <= float_info::max_k, + "k is out of range"); + return data::dragonbox_pow10_significands_64[k - float_info::min_k]; + } + + static carrier_uint compute_mul(carrier_uint u, + const cache_entry_type& cache) FMT_NOEXCEPT { + return umul96_upper32(u, cache); + } + + static uint32_t compute_delta(const cache_entry_type& cache, + int beta_minus_1) FMT_NOEXCEPT { + return static_cast(cache >> (64 - 1 - beta_minus_1)); + } + + static bool compute_mul_parity(carrier_uint two_f, + const cache_entry_type& cache, + int beta_minus_1) FMT_NOEXCEPT { + FMT_ASSERT(beta_minus_1 >= 1, ""); + FMT_ASSERT(beta_minus_1 < 64, ""); + + return ((umul96_lower64(two_f, cache) >> (64 - beta_minus_1)) & 1) != 0; + } + + static carrier_uint compute_left_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT { + return static_cast( + (cache - (cache >> (float_info::significand_bits + 2))) >> + (64 - float_info::significand_bits - 1 - beta_minus_1)); + } + + static carrier_uint compute_right_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT { + return static_cast( + (cache + (cache >> (float_info::significand_bits + 1))) >> + (64 - float_info::significand_bits - 1 - beta_minus_1)); + } + + static carrier_uint compute_round_up_for_shorter_interval_case( + const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT { + return (static_cast( + cache >> + (64 - float_info::significand_bits - 2 - beta_minus_1)) + + 1) / + 2; + } +}; + +template <> struct cache_accessor { + using carrier_uint = float_info::carrier_uint; + using cache_entry_type = uint128_wrapper; + + static uint128_wrapper get_cached_power(int k) FMT_NOEXCEPT { + FMT_ASSERT(k >= float_info::min_k && k <= float_info::max_k, + "k is out of range"); + +#if FMT_USE_FULL_CACHE_DRAGONBOX + return data::dragonbox_pow10_significands_128[k - + float_info::min_k]; +#else + static const int compression_ratio = 27; + + // Compute base index. + int cache_index = (k - float_info::min_k) / compression_ratio; + int kb = cache_index * compression_ratio + float_info::min_k; + int offset = k - kb; + + // Get base cache. + uint128_wrapper base_cache = + data::dragonbox_pow10_significands_128[cache_index]; + if (offset == 0) return base_cache; + + // Compute the required amount of bit-shift. + int alpha = floor_log2_pow10(kb + offset) - floor_log2_pow10(kb) - offset; + FMT_ASSERT(alpha > 0 && alpha < 64, "shifting error detected"); + + // Try to recover the real cache. + uint64_t pow5 = data::powers_of_5_64[offset]; + uint128_wrapper recovered_cache = umul128(base_cache.high(), pow5); + uint128_wrapper middle_low = + umul128(base_cache.low() - (kb < 0 ? 1 : 0), pow5); + + recovered_cache += middle_low.high(); + + uint64_t high_to_middle = recovered_cache.high() << (64 - alpha); + uint64_t middle_to_low = recovered_cache.low() << (64 - alpha); + + recovered_cache = + uint128_wrapper{(recovered_cache.low() >> alpha) | high_to_middle, + ((middle_low.low() >> alpha) | middle_to_low)}; + + if (kb < 0) recovered_cache += 1; + + // Get error. + int error_idx = (k - float_info::min_k) / 16; + uint32_t error = (data::dragonbox_pow10_recovery_errors[error_idx] >> + ((k - float_info::min_k) % 16) * 2) & + 0x3; + + // Add the error back. + FMT_ASSERT(recovered_cache.low() + error >= recovered_cache.low(), ""); + return {recovered_cache.high(), recovered_cache.low() + error}; +#endif + } + + static carrier_uint compute_mul(carrier_uint u, + const cache_entry_type& cache) FMT_NOEXCEPT { + return umul192_upper64(u, cache); + } + + static uint32_t compute_delta(cache_entry_type const& cache, + int beta_minus_1) FMT_NOEXCEPT { + return static_cast(cache.high() >> (64 - 1 - beta_minus_1)); + } + + static bool compute_mul_parity(carrier_uint two_f, + const cache_entry_type& cache, + int beta_minus_1) FMT_NOEXCEPT { + FMT_ASSERT(beta_minus_1 >= 1, ""); + FMT_ASSERT(beta_minus_1 < 64, ""); + + return ((umul192_middle64(two_f, cache) >> (64 - beta_minus_1)) & 1) != 0; + } + + static carrier_uint compute_left_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT { + return (cache.high() - + (cache.high() >> (float_info::significand_bits + 2))) >> + (64 - float_info::significand_bits - 1 - beta_minus_1); + } + + static carrier_uint compute_right_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT { + return (cache.high() + + (cache.high() >> (float_info::significand_bits + 1))) >> + (64 - float_info::significand_bits - 1 - beta_minus_1); + } + + static carrier_uint compute_round_up_for_shorter_interval_case( + const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT { + return ((cache.high() >> + (64 - float_info::significand_bits - 2 - beta_minus_1)) + + 1) / + 2; + } +}; + +// Various integer checks +template +bool is_left_endpoint_integer_shorter_interval(int exponent) FMT_NOEXCEPT { + return exponent >= + float_info< + T>::case_shorter_interval_left_endpoint_lower_threshold && + exponent <= + float_info::case_shorter_interval_left_endpoint_upper_threshold; +} +template +bool is_endpoint_integer(typename float_info::carrier_uint two_f, + int exponent, int minus_k) FMT_NOEXCEPT { + if (exponent < float_info::case_fc_pm_half_lower_threshold) return false; + // For k >= 0. + if (exponent <= float_info::case_fc_pm_half_upper_threshold) return true; + // For k < 0. + if (exponent > float_info::divisibility_check_by_5_threshold) return false; + return divisible_by_power_of_5(two_f, minus_k); +} + +template +bool is_center_integer(typename float_info::carrier_uint two_f, int exponent, + int minus_k) FMT_NOEXCEPT { + // Exponent for 5 is negative. + if (exponent > float_info::divisibility_check_by_5_threshold) return false; + if (exponent > float_info::case_fc_upper_threshold) + return divisible_by_power_of_5(two_f, minus_k); + // Both exponents are nonnegative. + if (exponent >= float_info::case_fc_lower_threshold) return true; + // Exponent for 2 is negative. + return divisible_by_power_of_2(two_f, minus_k - exponent + 1); +} + +// Remove trailing zeros from n and return the number of zeros removed (float) +FMT_ALWAYS_INLINE int remove_trailing_zeros(uint32_t& n) FMT_NOEXCEPT { +#ifdef FMT_BUILTIN_CTZ + int t = FMT_BUILTIN_CTZ(n); +#else + int t = ctz(n); +#endif + if (t > float_info::max_trailing_zeros) + t = float_info::max_trailing_zeros; + + const uint32_t mod_inv1 = 0xcccccccd; + const uint32_t max_quotient1 = 0x33333333; + const uint32_t mod_inv2 = 0xc28f5c29; + const uint32_t max_quotient2 = 0x0a3d70a3; + + int s = 0; + for (; s < t - 1; s += 2) { + if (n * mod_inv2 > max_quotient2) break; + n *= mod_inv2; + } + if (s < t && n * mod_inv1 <= max_quotient1) { + n *= mod_inv1; + ++s; + } + n >>= s; + return s; +} + +// Removes trailing zeros and returns the number of zeros removed (double) +FMT_ALWAYS_INLINE int remove_trailing_zeros(uint64_t& n) FMT_NOEXCEPT { +#ifdef FMT_BUILTIN_CTZLL + int t = FMT_BUILTIN_CTZLL(n); +#else + int t = ctzll(n); +#endif + if (t > float_info::max_trailing_zeros) + t = float_info::max_trailing_zeros; + // Divide by 10^8 and reduce to 32-bits + // Since ret_value.significand <= (2^64 - 1) / 1000 < 10^17, + // both of the quotient and the r should fit in 32-bits + + const uint32_t mod_inv1 = 0xcccccccd; + const uint32_t max_quotient1 = 0x33333333; + const uint64_t mod_inv8 = 0xc767074b22e90e21; + const uint64_t max_quotient8 = 0x00002af31dc46118; + + // If the number is divisible by 1'0000'0000, work with the quotient + if (t >= 8) { + auto quotient_candidate = n * mod_inv8; + + if (quotient_candidate <= max_quotient8) { + auto quotient = static_cast(quotient_candidate >> 8); + + int s = 8; + for (; s < t; ++s) { + if (quotient * mod_inv1 > max_quotient1) break; + quotient *= mod_inv1; + } + quotient >>= (s - 8); + n = quotient; + return s; + } + } + + // Otherwise, work with the remainder + auto quotient = static_cast(n / 100000000); + auto remainder = static_cast(n - 100000000 * quotient); + + if (t == 0 || remainder * mod_inv1 > max_quotient1) { + return 0; + } + remainder *= mod_inv1; + + if (t == 1 || remainder * mod_inv1 > max_quotient1) { + n = (remainder >> 1) + quotient * 10000000ull; + return 1; + } + remainder *= mod_inv1; + + if (t == 2 || remainder * mod_inv1 > max_quotient1) { + n = (remainder >> 2) + quotient * 1000000ull; + return 2; + } + remainder *= mod_inv1; + + if (t == 3 || remainder * mod_inv1 > max_quotient1) { + n = (remainder >> 3) + quotient * 100000ull; + return 3; + } + remainder *= mod_inv1; + + if (t == 4 || remainder * mod_inv1 > max_quotient1) { + n = (remainder >> 4) + quotient * 10000ull; + return 4; + } + remainder *= mod_inv1; + + if (t == 5 || remainder * mod_inv1 > max_quotient1) { + n = (remainder >> 5) + quotient * 1000ull; + return 5; + } + remainder *= mod_inv1; + + if (t == 6 || remainder * mod_inv1 > max_quotient1) { + n = (remainder >> 6) + quotient * 100ull; + return 6; + } + remainder *= mod_inv1; + + n = (remainder >> 7) + quotient * 10ull; + return 7; +} + +// The main algorithm for shorter interval case +template +FMT_ALWAYS_INLINE FMT_SAFEBUFFERS decimal_fp shorter_interval_case( + int exponent) FMT_NOEXCEPT { + decimal_fp ret_value; + // Compute k and beta + const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent); + const int beta_minus_1 = exponent + floor_log2_pow10(-minus_k); + + // Compute xi and zi + using cache_entry_type = typename cache_accessor::cache_entry_type; + const cache_entry_type cache = cache_accessor::get_cached_power(-minus_k); + + auto xi = cache_accessor::compute_left_endpoint_for_shorter_interval_case( + cache, beta_minus_1); + auto zi = cache_accessor::compute_right_endpoint_for_shorter_interval_case( + cache, beta_minus_1); + + // If the left endpoint is not an integer, increase it + if (!is_left_endpoint_integer_shorter_interval(exponent)) ++xi; + + // Try bigger divisor + ret_value.significand = zi / 10; + + // If succeed, remove trailing zeros if necessary and return + if (ret_value.significand * 10 >= xi) { + ret_value.exponent = minus_k + 1; + ret_value.exponent += remove_trailing_zeros(ret_value.significand); + return ret_value; + } + + // Otherwise, compute the round-up of y + ret_value.significand = + cache_accessor::compute_round_up_for_shorter_interval_case( + cache, beta_minus_1); + ret_value.exponent = minus_k; + + // When tie occurs, choose one of them according to the rule + if (exponent >= float_info::shorter_interval_tie_lower_threshold && + exponent <= float_info::shorter_interval_tie_upper_threshold) { + ret_value.significand = ret_value.significand % 2 == 0 + ? ret_value.significand + : ret_value.significand - 1; + } else if (ret_value.significand < xi) { + ++ret_value.significand; + } + return ret_value; +} + +template +FMT_SAFEBUFFERS decimal_fp to_decimal(T x) FMT_NOEXCEPT { + // Step 1: integer promotion & Schubfach multiplier calculation. + + using carrier_uint = typename float_info::carrier_uint; + using cache_entry_type = typename cache_accessor::cache_entry_type; + auto br = bit_cast(x); + + // Extract significand bits and exponent bits. + const carrier_uint significand_mask = + (static_cast(1) << float_info::significand_bits) - 1; + carrier_uint significand = (br & significand_mask); + const carrier_uint exponent_mask = + ((static_cast(1) << float_info::exponent_bits) - 1) + << float_info::significand_bits; + int exponent = + static_cast((br & exponent_mask) >> float_info::significand_bits); + + if (exponent != 0) { // Check if normal. + exponent += float_info::exponent_bias - float_info::significand_bits; + + // Shorter interval case; proceed like Schubfach. + if (significand == 0) return shorter_interval_case(exponent); + + significand |= + (static_cast(1) << float_info::significand_bits); + } else { + // Subnormal case; the interval is always regular. + if (significand == 0) return {0, 0}; + exponent = float_info::min_exponent - float_info::significand_bits; + } + + const bool include_left_endpoint = (significand % 2 == 0); + const bool include_right_endpoint = include_left_endpoint; + + // Compute k and beta. + const int minus_k = floor_log10_pow2(exponent) - float_info::kappa; + const cache_entry_type cache = cache_accessor::get_cached_power(-minus_k); + const int beta_minus_1 = exponent + floor_log2_pow10(-minus_k); + + // Compute zi and deltai + // 10^kappa <= deltai < 10^(kappa + 1) + const uint32_t deltai = cache_accessor::compute_delta(cache, beta_minus_1); + const carrier_uint two_fc = significand << 1; + const carrier_uint two_fr = two_fc | 1; + const carrier_uint zi = + cache_accessor::compute_mul(two_fr << beta_minus_1, cache); + + // Step 2: Try larger divisor; remove trailing zeros if necessary + + // Using an upper bound on zi, we might be able to optimize the division + // better than the compiler; we are computing zi / big_divisor here + decimal_fp ret_value; + ret_value.significand = divide_by_10_to_kappa_plus_1(zi); + uint32_t r = static_cast(zi - float_info::big_divisor * + ret_value.significand); + + if (r > deltai) { + goto small_divisor_case_label; + } else if (r < deltai) { + // Exclude the right endpoint if necessary + if (r == 0 && !include_right_endpoint && + is_endpoint_integer(two_fr, exponent, minus_k)) { + --ret_value.significand; + r = float_info::big_divisor; + goto small_divisor_case_label; + } + } else { + // r == deltai; compare fractional parts + // Check conditions in the order different from the paper + // to take advantage of short-circuiting + const carrier_uint two_fl = two_fc - 1; + if ((!include_left_endpoint || + !is_endpoint_integer(two_fl, exponent, minus_k)) && + !cache_accessor::compute_mul_parity(two_fl, cache, beta_minus_1)) { + goto small_divisor_case_label; + } + } + ret_value.exponent = minus_k + float_info::kappa + 1; + + // We may need to remove trailing zeros + ret_value.exponent += remove_trailing_zeros(ret_value.significand); + return ret_value; + + // Step 3: Find the significand with the smaller divisor + +small_divisor_case_label: + ret_value.significand *= 10; + ret_value.exponent = minus_k + float_info::kappa; + + const uint32_t mask = (1u << float_info::kappa) - 1; + auto dist = r - (deltai / 2) + (float_info::small_divisor / 2); + + // Is dist divisible by 2^kappa? + if ((dist & mask) == 0) { + const bool approx_y_parity = + ((dist ^ (float_info::small_divisor / 2)) & 1) != 0; + dist >>= float_info::kappa; + + // Is dist divisible by 5^kappa? + if (check_divisibility_and_divide_by_pow5::kappa>(dist)) { + ret_value.significand += dist; + + // Check z^(f) >= epsilon^(f) + // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1, + // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f) + // Since there are only 2 possibilities, we only need to care about the + // parity. Also, zi and r should have the same parity since the divisor + // is an even number + if (cache_accessor::compute_mul_parity(two_fc, cache, beta_minus_1) != + approx_y_parity) { + --ret_value.significand; + } else { + // If z^(f) >= epsilon^(f), we might have a tie + // when z^(f) == epsilon^(f), or equivalently, when y is an integer + if (is_center_integer(two_fc, exponent, minus_k)) { + ret_value.significand = ret_value.significand % 2 == 0 + ? ret_value.significand + : ret_value.significand - 1; + } + } + } + // Is dist not divisible by 5^kappa? + else { + ret_value.significand += dist; + } + } + // Is dist not divisible by 2^kappa? + else { + // Since we know dist is small, we might be able to optimize the division + // better than the compiler; we are computing dist / small_divisor here + ret_value.significand += + small_division_by_pow10::kappa>(dist); + } + return ret_value; +} +} // namespace dragonbox + +// Formats value using a variation of the Fixed-Precision Positive +// Floating-Point Printout ((FPP)^2) algorithm by Steele & White: +// https://fmt.dev/p372-steele.pdf. +template +void fallback_format(Double d, int num_digits, bool binary32, buffer& buf, + int& exp10) { + bigint numerator; // 2 * R in (FPP)^2. + bigint denominator; // 2 * S in (FPP)^2. + // lower and upper are differences between value and corresponding boundaries. + bigint lower; // (M^- in (FPP)^2). + bigint upper_store; // upper's value if different from lower. + bigint* upper = nullptr; // (M^+ in (FPP)^2). + fp value; + // Shift numerator and denominator by an extra bit or two (if lower boundary + // is closer) to make lower and upper integers. This eliminates multiplication + // by 2 during later computations. + const bool is_predecessor_closer = + binary32 ? value.assign(static_cast(d)) : value.assign(d); + int shift = is_predecessor_closer ? 2 : 1; + uint64_t significand = value.f << shift; + if (value.e >= 0) { + numerator.assign(significand); + numerator <<= value.e; + lower.assign(1); + lower <<= value.e; + if (shift != 1) { + upper_store.assign(1); + upper_store <<= value.e + 1; + upper = &upper_store; + } + denominator.assign_pow10(exp10); + denominator <<= 1; + } else if (exp10 < 0) { + numerator.assign_pow10(-exp10); + lower.assign(numerator); + if (shift != 1) { + upper_store.assign(numerator); + upper_store <<= 1; + upper = &upper_store; + } + numerator *= significand; + denominator.assign(1); + denominator <<= shift - value.e; + } else { + numerator.assign(significand); + denominator.assign_pow10(exp10); + denominator <<= shift - value.e; + lower.assign(1); + if (shift != 1) { + upper_store.assign(1ULL << 1); + upper = &upper_store; + } + } + // Invariant: value == (numerator / denominator) * pow(10, exp10). + if (num_digits < 0) { + // Generate the shortest representation. + if (!upper) upper = &lower; + bool even = (value.f & 1) == 0; + num_digits = 0; + char* data = buf.data(); + for (;;) { + int digit = numerator.divmod_assign(denominator); + bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower. + // numerator + upper >[=] pow10: + bool high = add_compare(numerator, *upper, denominator) + even > 0; + data[num_digits++] = static_cast('0' + digit); + if (low || high) { + if (!low) { + ++data[num_digits - 1]; + } else if (high) { + int result = add_compare(numerator, numerator, denominator); + // Round half to even. + if (result > 0 || (result == 0 && (digit % 2) != 0)) + ++data[num_digits - 1]; + } + buf.try_resize(to_unsigned(num_digits)); + exp10 -= num_digits - 1; + return; + } + numerator *= 10; + lower *= 10; + if (upper != &lower) *upper *= 10; + } + } + // Generate the given number of digits. + exp10 -= num_digits - 1; + if (num_digits == 0) { + buf.try_resize(1); + denominator *= 10; + buf[0] = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0'; + return; + } + buf.try_resize(to_unsigned(num_digits)); + for (int i = 0; i < num_digits - 1; ++i) { + int digit = numerator.divmod_assign(denominator); + buf[i] = static_cast('0' + digit); + numerator *= 10; + } + int digit = numerator.divmod_assign(denominator); + auto result = add_compare(numerator, numerator, denominator); + if (result > 0 || (result == 0 && (digit % 2) != 0)) { + if (digit == 9) { + const auto overflow = '0' + 10; + buf[num_digits - 1] = overflow; + // Propagate the carry. + for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] == overflow) { + buf[0] = '1'; + ++exp10; + } + return; + } + ++digit; + } + buf[num_digits - 1] = static_cast('0' + digit); +} + +template +int format_float(T value, int precision, float_specs specs, buffer& buf) { + static_assert(!std::is_same::value, ""); + FMT_ASSERT(value >= 0, "value is negative"); + + const bool fixed = specs.format == float_format::fixed; + if (value <= 0) { // <= instead of == to silence a warning. + if (precision <= 0 || !fixed) { + buf.push_back('0'); + return 0; + } + buf.try_resize(to_unsigned(precision)); + std::uninitialized_fill_n(buf.data(), precision, '0'); + return -precision; + } + + if (!specs.use_grisu) return snprintf_float(value, precision, specs, buf); + + if (precision < 0) { + // Use Dragonbox for the shortest format. + if (specs.binary32) { + auto dec = dragonbox::to_decimal(static_cast(value)); + write(buffer_appender(buf), dec.significand); + return dec.exponent; + } + auto dec = dragonbox::to_decimal(static_cast(value)); + write(buffer_appender(buf), dec.significand); + return dec.exponent; + } + + // Use Grisu + Dragon4 for the given precision: + // https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf. + int exp = 0; + const int min_exp = -60; // alpha in Grisu. + int cached_exp10 = 0; // K in Grisu. + fp normalized = normalize(fp(value)); + const auto cached_pow = get_cached_power( + min_exp - (normalized.e + fp::significand_size), cached_exp10); + normalized = normalized * cached_pow; + // Limit precision to the maximum possible number of significant digits in an + // IEEE754 double because we don't need to generate zeros. + const int max_double_digits = 767; + if (precision > max_double_digits) precision = max_double_digits; + fixed_handler handler{buf.data(), 0, precision, -cached_exp10, fixed}; + if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) { + exp += handler.size - cached_exp10 - 1; + fallback_format(value, handler.precision, specs.binary32, buf, exp); + } else { + exp += handler.exp10; + buf.try_resize(to_unsigned(handler.size)); + } + if (!fixed && !specs.showpoint) { + // Remove trailing zeros. + auto num_digits = buf.size(); + while (num_digits > 0 && buf[num_digits - 1] == '0') { + --num_digits; + ++exp; + } + buf.try_resize(num_digits); + } + return exp; +} // namespace detail + +template +int snprintf_float(T value, int precision, float_specs specs, + buffer& buf) { + // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. + FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer"); + static_assert(!std::is_same::value, ""); + + // Subtract 1 to account for the difference in precision since we use %e for + // both general and exponent format. + if (specs.format == float_format::general || + specs.format == float_format::exp) + precision = (precision >= 0 ? precision : 6) - 1; + + // Build the format string. + enum { max_format_size = 7 }; // The longest format is "%#.*Le". + char format[max_format_size]; + char* format_ptr = format; + *format_ptr++ = '%'; + if (specs.showpoint && specs.format == float_format::hex) *format_ptr++ = '#'; + if (precision >= 0) { + *format_ptr++ = '.'; + *format_ptr++ = '*'; + } + if (std::is_same()) *format_ptr++ = 'L'; + *format_ptr++ = specs.format != float_format::hex + ? (specs.format == float_format::fixed ? 'f' : 'e') + : (specs.upper ? 'A' : 'a'); + *format_ptr = '\0'; + + // Format using snprintf. + auto offset = buf.size(); + for (;;) { + auto begin = buf.data() + offset; + auto capacity = buf.capacity() - offset; +#ifdef FMT_FUZZ + if (precision > 100000) + throw std::runtime_error( + "fuzz mode - avoid large allocation inside snprintf"); +#endif + // Suppress the warning about a nonliteral format string. + // Cannot use auto because of a bug in MinGW (#1532). + int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; + int result = precision >= 0 + ? snprintf_ptr(begin, capacity, format, precision, value) + : snprintf_ptr(begin, capacity, format, value); + if (result < 0) { + // The buffer will grow exponentially. + buf.try_reserve(buf.capacity() + 1); + continue; + } + auto size = to_unsigned(result); + // Size equal to capacity means that the last character was truncated. + if (size >= capacity) { + buf.try_reserve(size + offset + 1); // Add 1 for the terminating '\0'. + continue; + } + auto is_digit = [](char c) { return c >= '0' && c <= '9'; }; + if (specs.format == float_format::fixed) { + if (precision == 0) { + buf.try_resize(size); + return 0; + } + // Find and remove the decimal point. + auto end = begin + size, p = end; + do { + --p; + } while (is_digit(*p)); + int fraction_size = static_cast(end - p - 1); + std::memmove(p, p + 1, to_unsigned(fraction_size)); + buf.try_resize(size - 1); + return -fraction_size; + } + if (specs.format == float_format::hex) { + buf.try_resize(size + offset); + return 0; + } + // Find and parse the exponent. + auto end = begin + size, exp_pos = end; + do { + --exp_pos; + } while (*exp_pos != 'e'); + char sign = exp_pos[1]; + assert(sign == '+' || sign == '-'); + int exp = 0; + auto p = exp_pos + 2; // Skip 'e' and sign. + do { + assert(is_digit(*p)); + exp = exp * 10 + (*p++ - '0'); + } while (p != end); + if (sign == '-') exp = -exp; + int fraction_size = 0; + if (exp_pos != begin + 1) { + // Remove trailing zeros. + auto fraction_end = exp_pos - 1; + while (*fraction_end == '0') --fraction_end; + // Move the fractional part left to get rid of the decimal point. + fraction_size = static_cast(fraction_end - begin - 1); + std::memmove(begin + 1, begin + 2, to_unsigned(fraction_size)); + } + buf.try_resize(to_unsigned(fraction_size) + offset + 1); + return exp - fraction_size; + } +} + +// A public domain branchless UTF-8 decoder by Christopher Wellons: +// https://github.com/skeeto/branchless-utf8 +/* Decode the next character, c, from buf, reporting errors in e. + * + * Since this is a branchless decoder, four bytes will be read from the + * buffer regardless of the actual length of the next character. This + * means the buffer _must_ have at least three bytes of zero padding + * following the end of the data stream. + * + * Errors are reported in e, which will be non-zero if the parsed + * character was somehow invalid: invalid byte sequence, non-canonical + * encoding, or a surrogate half. + * + * The function returns a pointer to the next character. When an error + * occurs, this pointer will be a guess that depends on the particular + * error, but it will always advance at least one byte. + */ +inline const char* utf8_decode(const char* buf, uint32_t* c, int* e) { + static const char lengths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 2, 2, 2, 2, 3, 3, 4, 0}; + static const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07}; + static const uint32_t mins[] = {4194304, 0, 128, 2048, 65536}; + static const int shiftc[] = {0, 18, 12, 6, 0}; + static const int shifte[] = {0, 6, 4, 2, 0}; + + auto s = reinterpret_cast(buf); + int len = lengths[s[0] >> 3]; + + // Compute the pointer to the next character early so that the next + // iteration can start working on the next character. Neither Clang + // nor GCC figure out this reordering on their own. + const char* next = buf + len + !len; + + // Assume a four-byte character and load four bytes. Unused bits are + // shifted out. + *c = uint32_t(s[0] & masks[len]) << 18; + *c |= uint32_t(s[1] & 0x3f) << 12; + *c |= uint32_t(s[2] & 0x3f) << 6; + *c |= uint32_t(s[3] & 0x3f) << 0; + *c >>= shiftc[len]; + + // Accumulate the various error conditions. + *e = (*c < mins[len]) << 6; // non-canonical encoding + *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half? + *e |= (*c > 0x10FFFF) << 8; // out of range? + *e |= (s[1] & 0xc0) >> 2; + *e |= (s[2] & 0xc0) >> 4; + *e |= (s[3]) >> 6; + *e ^= 0x2a; // top two bits of each tail byte correct? + *e >>= shifte[len]; + + return next; +} + +struct stringifier { + template FMT_INLINE std::string operator()(T value) const { + return to_string(value); + } + std::string operator()(basic_format_arg::handle h) const { + memory_buffer buf; + format_parse_context parse_ctx({}); + format_context format_ctx(buffer_appender(buf), {}, {}); + h.format(parse_ctx, format_ctx); + return to_string(buf); + } +}; +} // namespace detail + +template <> struct formatter { + format_parse_context::iterator parse(format_parse_context& ctx) { + return ctx.begin(); + } + + format_context::iterator format(const detail::bigint& n, + format_context& ctx) { + auto out = ctx.out(); + bool first = true; + for (auto i = n.bigits_.size(); i > 0; --i) { + auto value = n.bigits_[i - 1u]; + if (first) { + out = format_to(out, "{:x}", value); + first = false; + continue; + } + out = format_to(out, "{:08x}", value); + } + if (n.exp_ > 0) + out = format_to(out, "p{}", n.exp_ * detail::bigint::bigit_bits); + return out; + } +}; + +FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) { + auto transcode = [this](const char* p) { + auto cp = uint32_t(); + auto error = 0; + p = utf8_decode(p, &cp, &error); + if (error != 0) FMT_THROW(std::runtime_error("invalid utf8")); + if (cp <= 0xFFFF) { + buffer_.push_back(static_cast(cp)); + } else { + cp -= 0x10000; + buffer_.push_back(static_cast(0xD800 + (cp >> 10))); + buffer_.push_back(static_cast(0xDC00 + (cp & 0x3FF))); + } + return p; + }; + auto p = s.data(); + const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars. + if (s.size() >= block_size) { + for (auto end = p + s.size() - block_size + 1; p < end;) p = transcode(p); + } + if (auto num_chars_left = s.data() + s.size() - p) { + char buf[2 * block_size - 1] = {}; + memcpy(buf, p, to_unsigned(num_chars_left)); + p = buf; + do { + p = transcode(p); + } while (p - buf < num_chars_left); + } + buffer_.push_back(0); +} + +FMT_FUNC void format_system_error(detail::buffer& out, int error_code, + string_view message) FMT_NOEXCEPT { + FMT_TRY { + memory_buffer buf; + buf.resize(inline_buffer_size); + for (;;) { + char* system_message = &buf[0]; + int result = + detail::safe_strerror(error_code, system_message, buf.size()); + if (result == 0) { + format_to(detail::buffer_appender(out), "{}: {}", message, + system_message); + return; + } + if (result != ERANGE) + break; // Can't get error message, report error code instead. + buf.resize(buf.size() * 2); + } + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +FMT_FUNC void detail::error_handler::on_error(const char* message) { + FMT_THROW(format_error(message)); +} + +FMT_FUNC void report_system_error(int error_code, + fmt::string_view message) FMT_NOEXCEPT { + report_error(format_system_error, error_code, message); +} + +FMT_FUNC std::string detail::vformat(string_view format_str, format_args args) { + if (format_str.size() == 2 && equal2(format_str.data(), "{}")) { + auto arg = args.get(0); + if (!arg) error_handler().on_error("argument not found"); + return visit_format_arg(stringifier(), arg); + } + memory_buffer buffer; + detail::vformat_to(buffer, format_str, args); + return to_string(buffer); +} + +#ifdef _WIN32 +namespace detail { +using dword = conditional_t; +extern "C" __declspec(dllimport) int __stdcall WriteConsoleW( // + void*, const void*, dword, dword*, void*); +} // namespace detail +#endif + +FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) { + memory_buffer buffer; + detail::vformat_to(buffer, format_str, + basic_format_args>(args)); +#ifdef _WIN32 + auto fd = _fileno(f); + if (_isatty(fd)) { + detail::utf8_to_utf16 u16(string_view(buffer.data(), buffer.size())); + auto written = detail::dword(); + if (!detail::WriteConsoleW(reinterpret_cast(_get_osfhandle(fd)), + u16.c_str(), static_cast(u16.size()), + &written, nullptr)) { + FMT_THROW(format_error("failed to write to console")); + } + return; + } +#endif + detail::fwrite_fully(buffer.data(), 1, buffer.size(), f); +} + +#ifdef _WIN32 +// Print assuming legacy (non-Unicode) encoding. +FMT_FUNC void detail::vprint_mojibake(std::FILE* f, string_view format_str, + format_args args) { + memory_buffer buffer; + detail::vformat_to(buffer, format_str, + basic_format_args>(args)); + fwrite_fully(buffer.data(), 1, buffer.size(), f); +} +#endif + +FMT_FUNC void vprint(string_view format_str, format_args args) { + vprint(stdout, format_str, args); +} + +FMT_END_NAMESPACE + +#endif // FMT_FORMAT_INL_H_ diff --git a/src/3rdparty/fmt/format.cc b/src/3rdparty/fmt/format.cc new file mode 100644 index 00000000..52806fd7 --- /dev/null +++ b/src/3rdparty/fmt/format.cc @@ -0,0 +1,69 @@ +// Formatting library for C++ +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "3rdparty/fmt/format-inl.h" + +FMT_BEGIN_NAMESPACE +namespace detail { + +template +int format_float(char* buf, std::size_t size, const char* format, int precision, + T value) { +#ifdef FMT_FUZZ + if (precision > 100000) + throw std::runtime_error( + "fuzz mode - avoid large allocation inside snprintf"); +#endif + // Suppress the warning about nonliteral format string. + int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; + return precision < 0 ? snprintf_ptr(buf, size, format, value) + : snprintf_ptr(buf, size, format, precision, value); +} +} // namespace detail + +template struct FMT_INSTANTIATION_DEF_API detail::basic_data; + +// Workaround a bug in MSVC2013 that prevents instantiation of format_float. +int (*instantiate_format_float)(double, int, detail::float_specs, + detail::buffer&) = detail::format_float; + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +template FMT_API detail::locale_ref::locale_ref(const std::locale& loc); +template FMT_API std::locale detail::locale_ref::get() const; +#endif + +// Explicit instantiations for char. + +template FMT_API std::string detail::grouping_impl(locale_ref); +template FMT_API char detail::thousands_sep_impl(locale_ref); +template FMT_API char detail::decimal_point_impl(locale_ref); + +template FMT_API void detail::buffer::append(const char*, const char*); + +template FMT_API FMT_BUFFER_CONTEXT(char)::iterator detail::vformat_to( + detail::buffer&, string_view, + basic_format_args); + +template FMT_API int detail::snprintf_float(double, int, detail::float_specs, + detail::buffer&); +template FMT_API int detail::snprintf_float(long double, int, + detail::float_specs, + detail::buffer&); +template FMT_API int detail::format_float(double, int, detail::float_specs, + detail::buffer&); +template FMT_API int detail::format_float(long double, int, detail::float_specs, + detail::buffer&); + +// Explicit instantiations for wchar_t. + +template FMT_API std::string detail::grouping_impl(locale_ref); +template FMT_API wchar_t detail::thousands_sep_impl(locale_ref); +template FMT_API wchar_t detail::decimal_point_impl(locale_ref); + +template FMT_API void detail::buffer::append(const wchar_t*, + const wchar_t*); +FMT_END_NAMESPACE diff --git a/src/3rdparty/fmt/format.h b/src/3rdparty/fmt/format.h new file mode 100644 index 00000000..515851ee --- /dev/null +++ b/src/3rdparty/fmt/format.h @@ -0,0 +1,3869 @@ +/* + Formatting library for C++ + + Copyright (c) 2012 - present, Victor Zverovich + + 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. + + --- Optional exception to the license --- + + As an exception, if, as a result of your compiling your source code, portions + of this Software are embedded into a machine-executable object form of such + source code, you may redistribute such embedded portions in such object form + without including the above copyright and permission notices. + */ + +#ifndef FMT_FORMAT_H_ +#define FMT_FORMAT_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "core.h" + +#ifdef __INTEL_COMPILER +# define FMT_ICC_VERSION __INTEL_COMPILER +#elif defined(__ICL) +# define FMT_ICC_VERSION __ICL +#else +# define FMT_ICC_VERSION 0 +#endif + +#ifdef __NVCC__ +# define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__) +#else +# define FMT_CUDA_VERSION 0 +#endif + +#ifdef __has_builtin +# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#else +# define FMT_HAS_BUILTIN(x) 0 +#endif + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_NOINLINE __attribute__((noinline)) +#else +# define FMT_NOINLINE +#endif + +#if __cplusplus == 201103L || __cplusplus == 201402L +# if defined(__INTEL_COMPILER) || defined(__PGI) +# define FMT_FALLTHROUGH +# elif defined(__clang__) +# define FMT_FALLTHROUGH [[clang::fallthrough]] +# elif FMT_GCC_VERSION >= 700 && \ + (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520) +# define FMT_FALLTHROUGH [[gnu::fallthrough]] +# else +# define FMT_FALLTHROUGH +# endif +#elif FMT_HAS_CPP17_ATTRIBUTE(fallthrough) || \ + (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define FMT_FALLTHROUGH [[fallthrough]] +#else +# define FMT_FALLTHROUGH +#endif + +#ifndef FMT_MAYBE_UNUSED +# if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused) +# define FMT_MAYBE_UNUSED [[maybe_unused]] +# else +# define FMT_MAYBE_UNUSED +# endif +#endif + +#ifndef FMT_THROW +# if FMT_EXCEPTIONS +# if FMT_MSC_VER || FMT_NVCC +FMT_BEGIN_NAMESPACE +namespace detail { +template inline void do_throw(const Exception& x) { + // Silence unreachable code warnings in MSVC and NVCC because these + // are nearly impossible to fix in a generic code. + volatile bool b = true; + if (b) throw x; +} +} // namespace detail +FMT_END_NAMESPACE +# define FMT_THROW(x) detail::do_throw(x) +# else +# define FMT_THROW(x) throw x +# endif +# else +# define FMT_THROW(x) \ + do { \ + static_cast(sizeof(x)); \ + FMT_ASSERT(false, ""); \ + } while (false) +# endif +#endif + +#if FMT_EXCEPTIONS +# define FMT_TRY try +# define FMT_CATCH(x) catch (x) +#else +# define FMT_TRY if (true) +# define FMT_CATCH(x) if (false) +#endif + +#ifndef FMT_USE_USER_DEFINED_LITERALS +// EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs. +# if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \ + FMT_MSC_VER >= 1900) && \ + (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480) +# define FMT_USE_USER_DEFINED_LITERALS 1 +# else +# define FMT_USE_USER_DEFINED_LITERALS 0 +# endif +#endif + +#ifndef FMT_USE_UDL_TEMPLATE +// EDG frontend based compilers (icc, nvcc, PGI, etc) and GCC < 6.4 do not +// properly support UDL templates and GCC >= 9 warns about them. +# if FMT_USE_USER_DEFINED_LITERALS && \ + (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 501) && \ + ((FMT_GCC_VERSION >= 604 && __cplusplus >= 201402L) || \ + FMT_CLANG_VERSION >= 304) && \ + !defined(__PGI) && !defined(__NVCC__) +# define FMT_USE_UDL_TEMPLATE 1 +# else +# define FMT_USE_UDL_TEMPLATE 0 +# endif +#endif + +#ifndef FMT_USE_FLOAT +# define FMT_USE_FLOAT 1 +#endif + +#ifndef FMT_USE_DOUBLE +# define FMT_USE_DOUBLE 1 +#endif + +#ifndef FMT_USE_LONG_DOUBLE +# define FMT_USE_LONG_DOUBLE 1 +#endif + +// Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of +// int_writer template instances to just one by only using the largest integer +// type. This results in a reduction in binary size but will cause a decrease in +// integer formatting performance. +#if !defined(FMT_REDUCE_INT_INSTANTIATIONS) +# define FMT_REDUCE_INT_INSTANTIATIONS 0 +#endif + +// __builtin_clz is broken in clang with Microsoft CodeGen: +// https://github.com/fmtlib/fmt/issues/519 +#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clz)) && !FMT_MSC_VER +# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +#endif +#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clzll)) && !FMT_MSC_VER +# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +#endif +#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_ctz)) +# define FMT_BUILTIN_CTZ(n) __builtin_ctz(n) +#endif +#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_ctzll)) +# define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n) +#endif + +#if FMT_MSC_VER +# include // _BitScanReverse[64], _BitScanForward[64], _umul128 +#endif + +// Some compilers masquerade as both MSVC and GCC-likes or otherwise support +// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the +// MSVC intrinsics if the clz and clzll builtins are not available. +#if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && \ + !defined(FMT_BUILTIN_CTZLL) && !defined(_MANAGED) +FMT_BEGIN_NAMESPACE +namespace detail { +// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning. +# ifndef __clang__ +# pragma intrinsic(_BitScanForward) +# pragma intrinsic(_BitScanReverse) +# endif +# if defined(_WIN64) && !defined(__clang__) +# pragma intrinsic(_BitScanForward64) +# pragma intrinsic(_BitScanReverse64) +# endif + +inline int clz(uint32_t x) { + unsigned long r = 0; + _BitScanReverse(&r, x); + FMT_ASSERT(x != 0, ""); + // Static analysis complains about using uninitialized data + // "r", but the only way that can happen is if "x" is 0, + // which the callers guarantee to not happen. + FMT_SUPPRESS_MSC_WARNING(6102) + return 31 ^ static_cast(r); +} +# define FMT_BUILTIN_CLZ(n) detail::clz(n) + +inline int clzll(uint64_t x) { + unsigned long r = 0; +# ifdef _WIN64 + _BitScanReverse64(&r, x); +# else + // Scan the high 32 bits. + if (_BitScanReverse(&r, static_cast(x >> 32))) return 63 ^ (r + 32); + // Scan the low 32 bits. + _BitScanReverse(&r, static_cast(x)); +# endif + FMT_ASSERT(x != 0, ""); + FMT_SUPPRESS_MSC_WARNING(6102) // Suppress a bogus static analysis warning. + return 63 ^ static_cast(r); +} +# define FMT_BUILTIN_CLZLL(n) detail::clzll(n) + +inline int ctz(uint32_t x) { + unsigned long r = 0; + _BitScanForward(&r, x); + FMT_ASSERT(x != 0, ""); + FMT_SUPPRESS_MSC_WARNING(6102) // Suppress a bogus static analysis warning. + return static_cast(r); +} +# define FMT_BUILTIN_CTZ(n) detail::ctz(n) + +inline int ctzll(uint64_t x) { + unsigned long r = 0; + FMT_ASSERT(x != 0, ""); + FMT_SUPPRESS_MSC_WARNING(6102) // Suppress a bogus static analysis warning. +# ifdef _WIN64 + _BitScanForward64(&r, x); +# else + // Scan the low 32 bits. + if (_BitScanForward(&r, static_cast(x))) return static_cast(r); + // Scan the high 32 bits. + _BitScanForward(&r, static_cast(x >> 32)); + r += 32; +# endif + return static_cast(r); +} +# define FMT_BUILTIN_CTZLL(n) detail::ctzll(n) +} // namespace detail +FMT_END_NAMESPACE +#endif + +// Enable the deprecated numeric alignment. +#ifndef FMT_DEPRECATED_NUMERIC_ALIGN +# define FMT_DEPRECATED_NUMERIC_ALIGN 0 +#endif + +FMT_BEGIN_NAMESPACE +namespace detail { + +// An equivalent of `*reinterpret_cast(&source)` that doesn't have +// undefined behavior (e.g. due to type aliasing). +// Example: uint64_t d = bit_cast(2.718); +template +inline Dest bit_cast(const Source& source) { + static_assert(sizeof(Dest) == sizeof(Source), "size mismatch"); + Dest dest; + std::memcpy(&dest, &source, sizeof(dest)); + return dest; +} + +inline bool is_big_endian() { + const auto u = 1u; + struct bytes { + char data[sizeof(u)]; + }; + return bit_cast(u).data[0] == 0; +} + +// A fallback implementation of uintptr_t for systems that lack it. +struct fallback_uintptr { + unsigned char value[sizeof(void*)]; + + fallback_uintptr() = default; + explicit fallback_uintptr(const void* p) { + *this = bit_cast(p); + if (is_big_endian()) { + for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j) + std::swap(value[i], value[j]); + } + } +}; +#ifdef UINTPTR_MAX +using uintptr_t = ::uintptr_t; +inline uintptr_t to_uintptr(const void* p) { return bit_cast(p); } +#else +using uintptr_t = fallback_uintptr; +inline fallback_uintptr to_uintptr(const void* p) { + return fallback_uintptr(p); +} +#endif + +// Returns the largest possible value for type T. Same as +// std::numeric_limits::max() but shorter and not affected by the max macro. +template constexpr T max_value() { + return (std::numeric_limits::max)(); +} +template constexpr int num_bits() { + return std::numeric_limits::digits; +} +// std::numeric_limits::digits may return 0 for 128-bit ints. +template <> constexpr int num_bits() { return 128; } +template <> constexpr int num_bits() { return 128; } +template <> constexpr int num_bits() { + return static_cast(sizeof(void*) * + std::numeric_limits::digits); +} + +FMT_INLINE void assume(bool condition) { + (void)condition; +#if FMT_HAS_BUILTIN(__builtin_assume) + __builtin_assume(condition); +#endif +} + +// An approximation of iterator_t for pre-C++20 systems. +template +using iterator_t = decltype(std::begin(std::declval())); +template using sentinel_t = decltype(std::end(std::declval())); + +// A workaround for std::string not having mutable data() until C++17. +template inline Char* get_data(std::basic_string& s) { + return &s[0]; +} +template +inline typename Container::value_type* get_data(Container& c) { + return c.data(); +} + +#if defined(_SECURE_SCL) && _SECURE_SCL +// Make a checked iterator to avoid MSVC warnings. +template using checked_ptr = stdext::checked_array_iterator; +template checked_ptr make_checked(T* p, size_t size) { + return {p, size}; +} +#else +template using checked_ptr = T*; +template inline T* make_checked(T* p, size_t) { return p; } +#endif + +template ::value)> +#if FMT_CLANG_VERSION +__attribute__((no_sanitize("undefined"))) +#endif +inline checked_ptr +reserve(std::back_insert_iterator it, size_t n) { + Container& c = get_container(it); + size_t size = c.size(); + c.resize(size + n); + return make_checked(get_data(c) + size, n); +} + +template +inline buffer_appender reserve(buffer_appender it, size_t n) { + buffer& buf = get_container(it); + buf.try_reserve(buf.size() + n); + return it; +} + +template inline Iterator& reserve(Iterator& it, size_t) { + return it; +} + +template +constexpr T* to_pointer(OutputIt, size_t) { + return nullptr; +} +template T* to_pointer(buffer_appender it, size_t n) { + buffer& buf = get_container(it); + auto size = buf.size(); + if (buf.capacity() < size + n) return nullptr; + buf.try_resize(size + n); + return buf.data() + size; +} + +template ::value)> +inline std::back_insert_iterator base_iterator( + std::back_insert_iterator& it, + checked_ptr) { + return it; +} + +template +inline Iterator base_iterator(Iterator, Iterator it) { + return it; +} + +// An output iterator that counts the number of objects written to it and +// discards them. +class counting_iterator { + private: + size_t count_; + + public: + using iterator_category = std::output_iterator_tag; + using difference_type = std::ptrdiff_t; + using pointer = void; + using reference = void; + using _Unchecked_type = counting_iterator; // Mark iterator as checked. + + struct value_type { + template void operator=(const T&) {} + }; + + counting_iterator() : count_(0) {} + + size_t count() const { return count_; } + + counting_iterator& operator++() { + ++count_; + return *this; + } + counting_iterator operator++(int) { + auto it = *this; + ++*this; + return it; + } + + friend counting_iterator operator+(counting_iterator it, difference_type n) { + it.count_ += static_cast(n); + return it; + } + + value_type operator*() const { return {}; } +}; + +template class truncating_iterator_base { + protected: + OutputIt out_; + size_t limit_; + size_t count_; + + truncating_iterator_base(OutputIt out, size_t limit) + : out_(out), limit_(limit), count_(0) {} + + public: + using iterator_category = std::output_iterator_tag; + using value_type = typename std::iterator_traits::value_type; + using difference_type = void; + using pointer = void; + using reference = void; + using _Unchecked_type = + truncating_iterator_base; // Mark iterator as checked. + + OutputIt base() const { return out_; } + size_t count() const { return count_; } +}; + +// An output iterator that truncates the output and counts the number of objects +// written to it. +template ::value_type>::type> +class truncating_iterator; + +template +class truncating_iterator + : public truncating_iterator_base { + mutable typename truncating_iterator_base::value_type blackhole_; + + public: + using value_type = typename truncating_iterator_base::value_type; + + truncating_iterator(OutputIt out, size_t limit) + : truncating_iterator_base(out, limit) {} + + truncating_iterator& operator++() { + if (this->count_++ < this->limit_) ++this->out_; + return *this; + } + + truncating_iterator operator++(int) { + auto it = *this; + ++*this; + return it; + } + + value_type& operator*() const { + return this->count_ < this->limit_ ? *this->out_ : blackhole_; + } +}; + +template +class truncating_iterator + : public truncating_iterator_base { + public: + truncating_iterator(OutputIt out, size_t limit) + : truncating_iterator_base(out, limit) {} + + template truncating_iterator& operator=(T val) { + if (this->count_++ < this->limit_) *this->out_++ = val; + return *this; + } + + truncating_iterator& operator++() { return *this; } + truncating_iterator& operator++(int) { return *this; } + truncating_iterator& operator*() { return *this; } +}; + +template +inline size_t count_code_points(basic_string_view s) { + return s.size(); +} + +// Counts the number of code points in a UTF-8 string. +inline size_t count_code_points(basic_string_view s) { + const char* data = s.data(); + size_t num_code_points = 0; + for (size_t i = 0, size = s.size(); i != size; ++i) { + if ((data[i] & 0xc0) != 0x80) ++num_code_points; + } + return num_code_points; +} + +inline size_t count_code_points(basic_string_view s) { + return count_code_points(basic_string_view( + reinterpret_cast(s.data()), s.size())); +} + +template +inline size_t code_point_index(basic_string_view s, size_t n) { + size_t size = s.size(); + return n < size ? n : size; +} + +// Calculates the index of the nth code point in a UTF-8 string. +inline size_t code_point_index(basic_string_view s, size_t n) { + const char8_type* data = s.data(); + size_t num_code_points = 0; + for (size_t i = 0, size = s.size(); i != size; ++i) { + if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) { + return i; + } + } + return s.size(); +} + +template +using needs_conversion = bool_constant< + std::is_same::value_type, + char>::value && + std::is_same::value>; + +template ::value)> +OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::copy(begin, end, it); +} + +template ::value)> +OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::transform(begin, end, it, + [](char c) { return static_cast(c); }); +} + +template +inline counting_iterator copy_str(InputIt begin, InputIt end, + counting_iterator it) { + return it + (end - begin); +} + +template +using is_fast_float = bool_constant::is_iec559 && + sizeof(T) <= sizeof(double)>; + +#ifndef FMT_USE_FULL_CACHE_DRAGONBOX +# define FMT_USE_FULL_CACHE_DRAGONBOX 0 +#endif + +template +template +void buffer::append(const U* begin, const U* end) { + do { + auto count = to_unsigned(end - begin); + try_reserve(size_ + count); + auto free_cap = capacity_ - size_; + if (free_cap < count) count = free_cap; + std::uninitialized_copy_n(begin, count, make_checked(ptr_ + size_, count)); + size_ += count; + begin += count; + } while (begin != end); +} + +template +void iterator_buffer::flush() { + out_ = std::copy_n(data_, this->limit(this->size()), out_); + this->clear(); +} +} // namespace detail + +// The number of characters to store in the basic_memory_buffer object itself +// to avoid dynamic memory allocation. +enum { inline_buffer_size = 500 }; + +/** + \rst + A dynamically growing memory buffer for trivially copyable/constructible types + with the first ``SIZE`` elements stored in the object itself. + + You can use one of the following type aliases for common character types: + + +----------------+------------------------------+ + | Type | Definition | + +================+==============================+ + | memory_buffer | basic_memory_buffer | + +----------------+------------------------------+ + | wmemory_buffer | basic_memory_buffer | + +----------------+------------------------------+ + + **Example**:: + + fmt::memory_buffer out; + format_to(out, "The answer is {}.", 42); + + This will append the following output to the ``out`` object: + + .. code-block:: none + + The answer is 42. + + The output can be converted to an ``std::string`` with ``to_string(out)``. + \endrst + */ +template > +class basic_memory_buffer : public detail::buffer { + private: + T store_[SIZE]; + + // Don't inherit from Allocator avoid generating type_info for it. + Allocator alloc_; + + // Deallocate memory allocated by the buffer. + void deallocate() { + T* data = this->data(); + if (data != store_) alloc_.deallocate(data, this->capacity()); + } + + protected: + void grow(size_t size) final FMT_OVERRIDE; + + public: + using value_type = T; + using const_reference = const T&; + + explicit basic_memory_buffer(const Allocator& alloc = Allocator()) + : alloc_(alloc) { + this->set(store_, SIZE); + } + ~basic_memory_buffer() { deallocate(); } + + private: + // Move data from other to this buffer. + void move(basic_memory_buffer& other) { + alloc_ = std::move(other.alloc_); + T* data = other.data(); + size_t size = other.size(), capacity = other.capacity(); + if (data == other.store_) { + this->set(store_, capacity); + std::uninitialized_copy(other.store_, other.store_ + size, + detail::make_checked(store_, capacity)); + } else { + this->set(data, capacity); + // Set pointer to the inline array so that delete is not called + // when deallocating. + other.set(other.store_, 0); + } + this->resize(size); + } + + public: + /** + \rst + Constructs a :class:`fmt::basic_memory_buffer` object moving the content + of the other object to it. + \endrst + */ + basic_memory_buffer(basic_memory_buffer&& other) FMT_NOEXCEPT { move(other); } + + /** + \rst + Moves the content of the other ``basic_memory_buffer`` object to this one. + \endrst + */ + basic_memory_buffer& operator=(basic_memory_buffer&& other) FMT_NOEXCEPT { + FMT_ASSERT(this != &other, ""); + deallocate(); + move(other); + return *this; + } + + // Returns a copy of the allocator associated with this buffer. + Allocator get_allocator() const { return alloc_; } + + /** + Resizes the buffer to contain *count* elements. If T is a POD type new + elements may not be initialized. + */ + void resize(size_t count) { this->try_resize(count); } + + /** Increases the buffer capacity to *new_capacity*. */ + void reserve(size_t new_capacity) { this->try_reserve(new_capacity); } + + // Directly append data into the buffer + using detail::buffer::append; + template + void append(const ContiguousRange& range) { + append(range.data(), range.data() + range.size()); + } +}; + +template +void basic_memory_buffer::grow(size_t size) { +#ifdef FMT_FUZZ + if (size > 5000) throw std::runtime_error("fuzz mode - won't grow that much"); +#endif + size_t old_capacity = this->capacity(); + size_t new_capacity = old_capacity + old_capacity / 2; + if (size > new_capacity) new_capacity = size; + T* old_data = this->data(); + T* new_data = + std::allocator_traits::allocate(alloc_, new_capacity); + // The following code doesn't throw, so the raw pointer above doesn't leak. + std::uninitialized_copy(old_data, old_data + this->size(), + detail::make_checked(new_data, new_capacity)); + this->set(new_data, new_capacity); + // deallocate must not throw according to the standard, but even if it does, + // the buffer already uses the new storage and will deallocate it in + // destructor. + if (old_data != store_) alloc_.deallocate(old_data, old_capacity); +} + +using memory_buffer = basic_memory_buffer; +using wmemory_buffer = basic_memory_buffer; + +template +struct is_contiguous> : std::true_type { +}; + +/** A formatting error such as invalid format string. */ +FMT_CLASS_API +class FMT_API format_error : public std::runtime_error { + public: + explicit format_error(const char* message) : std::runtime_error(message) {} + explicit format_error(const std::string& message) + : std::runtime_error(message) {} + format_error(const format_error&) = default; + format_error& operator=(const format_error&) = default; + format_error(format_error&&) = default; + format_error& operator=(format_error&&) = default; + ~format_error() FMT_NOEXCEPT FMT_OVERRIDE; +}; + +namespace detail { + +template +using is_signed = + std::integral_constant::is_signed || + std::is_same::value>; + +// Returns true if value is negative, false otherwise. +// Same as `value < 0` but doesn't produce warnings if T is an unsigned type. +template ::value)> +FMT_CONSTEXPR bool is_negative(T value) { + return value < 0; +} +template ::value)> +FMT_CONSTEXPR bool is_negative(T) { + return false; +} + +template ::value)> +FMT_CONSTEXPR bool is_supported_floating_point(T) { + return (std::is_same::value && FMT_USE_FLOAT) || + (std::is_same::value && FMT_USE_DOUBLE) || + (std::is_same::value && FMT_USE_LONG_DOUBLE); +} + +// Smallest of uint32_t, uint64_t, uint128_t that is large enough to +// represent all values of an integral type T. +template +using uint32_or_64_or_128_t = + conditional_t() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS, + uint32_t, + conditional_t() <= 64, uint64_t, uint128_t>>; + +// 128-bit integer type used internally +struct FMT_EXTERN_TEMPLATE_API uint128_wrapper { + uint128_wrapper() = default; + +#if FMT_USE_INT128 + uint128_t internal_; + + uint128_wrapper(uint64_t high, uint64_t low) FMT_NOEXCEPT + : internal_{static_cast(low) | + (static_cast(high) << 64)} {} + + uint128_wrapper(uint128_t u) : internal_{u} {} + + uint64_t high() const FMT_NOEXCEPT { return uint64_t(internal_ >> 64); } + uint64_t low() const FMT_NOEXCEPT { return uint64_t(internal_); } + + uint128_wrapper& operator+=(uint64_t n) & FMT_NOEXCEPT { + internal_ += n; + return *this; + } +#else + uint64_t high_; + uint64_t low_; + + uint128_wrapper(uint64_t high, uint64_t low) FMT_NOEXCEPT : high_{high}, + low_{low} {} + + uint64_t high() const FMT_NOEXCEPT { return high_; } + uint64_t low() const FMT_NOEXCEPT { return low_; } + + uint128_wrapper& operator+=(uint64_t n) & FMT_NOEXCEPT { +# if defined(_MSC_VER) && defined(_M_X64) + unsigned char carry = _addcarry_u64(0, low_, n, &low_); + _addcarry_u64(carry, high_, 0, &high_); + return *this; +# else + uint64_t sum = low_ + n; + high_ += (sum < low_ ? 1 : 0); + low_ = sum; + return *this; +# endif + } +#endif +}; + +// Table entry type for divisibility test used internally +template struct FMT_EXTERN_TEMPLATE_API divtest_table_entry { + T mod_inv; + T max_quotient; +}; + +// Static data is placed in this class template for the header-only config. +template struct FMT_EXTERN_TEMPLATE_API basic_data { + static const uint64_t powers_of_10_64[]; + static const uint32_t zero_or_powers_of_10_32[]; + static const uint64_t zero_or_powers_of_10_64[]; + static const uint64_t grisu_pow10_significands[]; + static const int16_t grisu_pow10_exponents[]; + static const divtest_table_entry divtest_table_for_pow5_32[]; + static const divtest_table_entry divtest_table_for_pow5_64[]; + static const uint64_t dragonbox_pow10_significands_64[]; + static const uint128_wrapper dragonbox_pow10_significands_128[]; + // log10(2) = 0x0.4d104d427de7fbcc... + static const uint64_t log10_2_significand = 0x4d104d427de7fbcc; +#if !FMT_USE_FULL_CACHE_DRAGONBOX + static const uint64_t powers_of_5_64[]; + static const uint32_t dragonbox_pow10_recovery_errors[]; +#endif + // GCC generates slightly better code for pairs than chars. + using digit_pair = char[2]; + static const digit_pair digits[]; + static const char hex_digits[]; + static const char foreground_color[]; + static const char background_color[]; + static const char reset_color[5]; + static const wchar_t wreset_color[5]; + static const char signs[]; + static const char left_padding_shifts[5]; + static const char right_padding_shifts[5]; +}; + +// Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)). +// This is a function instead of an array to workaround a bug in GCC10 (#1810). +FMT_INLINE uint16_t bsr2log10(int bsr) { + static constexpr uint16_t data[] = { + 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, + 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, + 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15, + 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20}; + return data[bsr]; +} + +#ifndef FMT_EXPORTED +FMT_EXTERN template struct basic_data; +#endif + +// This is a struct rather than an alias to avoid shadowing warnings in gcc. +struct data : basic_data<> {}; + +#ifdef FMT_BUILTIN_CLZLL +// Returns the number of decimal digits in n. Leading zeros are not counted +// except for n == 0 in which case count_digits returns 1. +inline int count_digits(uint64_t n) { + // https://github.com/fmtlib/format-benchmark/blob/master/digits10 + auto t = bsr2log10(FMT_BUILTIN_CLZLL(n | 1) ^ 63); + return t - (n < data::zero_or_powers_of_10_64[t]); +} +#else +// Fallback version of count_digits used when __builtin_clz is not available. +inline int count_digits(uint64_t n) { + int count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000u; + count += 4; + } +} +#endif + +#if FMT_USE_INT128 +inline int count_digits(uint128_t n) { + int count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000U; + count += 4; + } +} +#endif + +// Counts the number of digits in n. BITS = log2(radix). +template inline int count_digits(UInt n) { + int num_digits = 0; + do { + ++num_digits; + } while ((n >>= BITS) != 0); + return num_digits; +} + +template <> int count_digits<4>(detail::fallback_uintptr n); + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_ALWAYS_INLINE inline __attribute__((always_inline)) +#elif FMT_MSC_VER +# define FMT_ALWAYS_INLINE __forceinline +#else +# define FMT_ALWAYS_INLINE inline +#endif + +// To suppress unnecessary security cookie checks +#if FMT_MSC_VER && !FMT_CLANG_VERSION +# define FMT_SAFEBUFFERS __declspec(safebuffers) +#else +# define FMT_SAFEBUFFERS +#endif + +#ifdef FMT_BUILTIN_CLZ +// Optional version of count_digits for better performance on 32-bit platforms. +inline int count_digits(uint32_t n) { + auto t = bsr2log10(FMT_BUILTIN_CLZ(n | 1) ^ 31); + return t - (n < data::zero_or_powers_of_10_32[t]); +} +#endif + +template constexpr int digits10() FMT_NOEXCEPT { + return std::numeric_limits::digits10; +} +template <> constexpr int digits10() FMT_NOEXCEPT { return 38; } +template <> constexpr int digits10() FMT_NOEXCEPT { return 38; } + +template FMT_API std::string grouping_impl(locale_ref loc); +template inline std::string grouping(locale_ref loc) { + return grouping_impl(loc); +} +template <> inline std::string grouping(locale_ref loc) { + return grouping_impl(loc); +} + +template FMT_API Char thousands_sep_impl(locale_ref loc); +template inline Char thousands_sep(locale_ref loc) { + return Char(thousands_sep_impl(loc)); +} +template <> inline wchar_t thousands_sep(locale_ref loc) { + return thousands_sep_impl(loc); +} + +template FMT_API Char decimal_point_impl(locale_ref loc); +template inline Char decimal_point(locale_ref loc) { + return Char(decimal_point_impl(loc)); +} +template <> inline wchar_t decimal_point(locale_ref loc) { + return decimal_point_impl(loc); +} + +// Compares two characters for equality. +template bool equal2(const Char* lhs, const char* rhs) { + return lhs[0] == rhs[0] && lhs[1] == rhs[1]; +} +inline bool equal2(const char* lhs, const char* rhs) { + return memcmp(lhs, rhs, 2) == 0; +} + +// Copies two characters from src to dst. +template void copy2(Char* dst, const char* src) { + *dst++ = static_cast(*src++); + *dst = static_cast(*src); +} +inline void copy2(char* dst, const char* src) { memcpy(dst, src, 2); } + +template struct format_decimal_result { + Iterator begin; + Iterator end; +}; + +// Formats a decimal unsigned integer value writing into out pointing to a +// buffer of specified size. The caller must ensure that the buffer is large +// enough. +template +inline format_decimal_result format_decimal(Char* out, UInt value, + int size) { + FMT_ASSERT(size >= count_digits(value), "invalid digit count"); + out += size; + Char* end = out; + while (value >= 100) { + // Integer division is slow so do it for a group of two digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + out -= 2; + copy2(out, data::digits[value % 100]); + value /= 100; + } + if (value < 10) { + *--out = static_cast('0' + value); + return {out, end}; + } + out -= 2; + copy2(out, data::digits[value]); + return {out, end}; +} + +template >::value)> +inline format_decimal_result format_decimal(Iterator out, UInt value, + int num_digits) { + // Buffer should be large enough to hold all digits (<= digits10 + 1). + enum { max_size = digits10() + 1 }; + Char buffer[2 * max_size]; + auto end = format_decimal(buffer, value, num_digits).end; + return {out, detail::copy_str(buffer, end, out)}; +} + +template +inline Char* format_uint(Char* buffer, UInt value, int num_digits, + bool upper = false) { + buffer += num_digits; + Char* end = buffer; + do { + const char* digits = upper ? "0123456789ABCDEF" : data::hex_digits; + unsigned digit = (value & ((1 << BASE_BITS) - 1)); + *--buffer = static_cast(BASE_BITS < 4 ? static_cast('0' + digit) + : digits[digit]); + } while ((value >>= BASE_BITS) != 0); + return end; +} + +template +Char* format_uint(Char* buffer, detail::fallback_uintptr n, int num_digits, + bool = false) { + auto char_digits = std::numeric_limits::digits / 4; + int start = (num_digits + char_digits - 1) / char_digits - 1; + if (int start_digits = num_digits % char_digits) { + unsigned value = n.value[start--]; + buffer = format_uint(buffer, value, start_digits); + } + for (; start >= 0; --start) { + unsigned value = n.value[start]; + buffer += char_digits; + auto p = buffer; + for (int i = 0; i < char_digits; ++i) { + unsigned digit = (value & ((1 << BASE_BITS) - 1)); + *--p = static_cast(data::hex_digits[digit]); + value >>= BASE_BITS; + } + } + return buffer; +} + +template +inline It format_uint(It out, UInt value, int num_digits, bool upper = false) { + // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1). + char buffer[num_bits() / BASE_BITS + 1]; + format_uint(buffer, value, num_digits, upper); + return detail::copy_str(buffer, buffer + num_digits, out); +} + +// A converter from UTF-8 to UTF-16. +class utf8_to_utf16 { + private: + wmemory_buffer buffer_; + + public: + FMT_API explicit utf8_to_utf16(string_view s); + operator wstring_view() const { return {&buffer_[0], size()}; } + size_t size() const { return buffer_.size() - 1; } + const wchar_t* c_str() const { return &buffer_[0]; } + std::wstring str() const { return {&buffer_[0], size()}; } +}; + +template struct null {}; + +// Workaround an array initialization issue in gcc 4.8. +template struct fill_t { + private: + enum { max_size = 4 }; + Char data_[max_size]; + unsigned char size_; + + public: + FMT_CONSTEXPR void operator=(basic_string_view s) { + auto size = s.size(); + if (size > max_size) { + FMT_THROW(format_error("invalid fill")); + return; + } + for (size_t i = 0; i < size; ++i) data_[i] = s[i]; + size_ = static_cast(size); + } + + size_t size() const { return size_; } + const Char* data() const { return data_; } + + FMT_CONSTEXPR Char& operator[](size_t index) { return data_[index]; } + FMT_CONSTEXPR const Char& operator[](size_t index) const { + return data_[index]; + } + + static FMT_CONSTEXPR fill_t make() { + auto fill = fill_t(); + fill[0] = Char(' '); + fill.size_ = 1; + return fill; + } +}; +} // namespace detail + +// We cannot use enum classes as bit fields because of a gcc bug +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414. +namespace align { +enum type { none, left, right, center, numeric }; +} +using align_t = align::type; + +namespace sign { +enum type { none, minus, plus, space }; +} +using sign_t = sign::type; + +// Format specifiers for built-in and string types. +template struct basic_format_specs { + int width; + int precision; + char type; + align_t align : 4; + sign_t sign : 3; + bool alt : 1; // Alternate form ('#'). + detail::fill_t fill; + + constexpr basic_format_specs() + : width(0), + precision(-1), + type(0), + align(align::none), + sign(sign::none), + alt(false), + fill(detail::fill_t::make()) {} +}; + +using format_specs = basic_format_specs; + +namespace detail { +namespace dragonbox { + +// Type-specific information that Dragonbox uses. +template struct float_info; + +template <> struct float_info { + using carrier_uint = uint32_t; + static const int significand_bits = 23; + static const int exponent_bits = 8; + static const int min_exponent = -126; + static const int max_exponent = 127; + static const int exponent_bias = -127; + static const int decimal_digits = 9; + static const int kappa = 1; + static const int big_divisor = 100; + static const int small_divisor = 10; + static const int min_k = -31; + static const int max_k = 46; + static const int cache_bits = 64; + static const int divisibility_check_by_5_threshold = 39; + static const int case_fc_pm_half_lower_threshold = -1; + static const int case_fc_pm_half_upper_threshold = 6; + static const int case_fc_lower_threshold = -2; + static const int case_fc_upper_threshold = 6; + static const int case_shorter_interval_left_endpoint_lower_threshold = 2; + static const int case_shorter_interval_left_endpoint_upper_threshold = 3; + static const int shorter_interval_tie_lower_threshold = -35; + static const int shorter_interval_tie_upper_threshold = -35; + static const int max_trailing_zeros = 7; +}; + +template <> struct float_info { + using carrier_uint = uint64_t; + static const int significand_bits = 52; + static const int exponent_bits = 11; + static const int min_exponent = -1022; + static const int max_exponent = 1023; + static const int exponent_bias = -1023; + static const int decimal_digits = 17; + static const int kappa = 2; + static const int big_divisor = 1000; + static const int small_divisor = 100; + static const int min_k = -292; + static const int max_k = 326; + static const int cache_bits = 128; + static const int divisibility_check_by_5_threshold = 86; + static const int case_fc_pm_half_lower_threshold = -2; + static const int case_fc_pm_half_upper_threshold = 9; + static const int case_fc_lower_threshold = -4; + static const int case_fc_upper_threshold = 9; + static const int case_shorter_interval_left_endpoint_lower_threshold = 2; + static const int case_shorter_interval_left_endpoint_upper_threshold = 3; + static const int shorter_interval_tie_lower_threshold = -77; + static const int shorter_interval_tie_upper_threshold = -77; + static const int max_trailing_zeros = 16; +}; + +template struct decimal_fp { + using significand_type = typename float_info::carrier_uint; + significand_type significand; + int exponent; +}; + +template decimal_fp to_decimal(T x) FMT_NOEXCEPT; +} // namespace dragonbox + +// A floating-point presentation format. +enum class float_format : unsigned char { + general, // General: exponent notation or fixed point based on magnitude. + exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3. + fixed, // Fixed point with the default precision of 6, e.g. 0.0012. + hex +}; + +struct float_specs { + int precision; + float_format format : 8; + sign_t sign : 8; + bool upper : 1; + bool locale : 1; + bool binary32 : 1; + bool use_grisu : 1; + bool showpoint : 1; +}; + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template It write_exponent(int exp, It it) { + FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range"); + if (exp < 0) { + *it++ = static_cast('-'); + exp = -exp; + } else { + *it++ = static_cast('+'); + } + if (exp >= 100) { + const char* top = data::digits[exp / 100]; + if (exp >= 1000) *it++ = static_cast(top[0]); + *it++ = static_cast(top[1]); + exp %= 100; + } + const char* d = data::digits[exp]; + *it++ = static_cast(d[0]); + *it++ = static_cast(d[1]); + return it; +} + +template +int format_float(T value, int precision, float_specs specs, buffer& buf); + +// Formats a floating-point number with snprintf. +template +int snprintf_float(T value, int precision, float_specs specs, + buffer& buf); + +template T promote_float(T value) { return value; } +inline double promote_float(float value) { return static_cast(value); } + +template +FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) { + switch (spec) { + case 0: + case 'd': + handler.on_dec(); + break; + case 'x': + case 'X': + handler.on_hex(); + break; + case 'b': + case 'B': + handler.on_bin(); + break; + case 'o': + handler.on_oct(); + break; +#ifdef FMT_DEPRECATED_N_SPECIFIER + case 'n': +#endif + case 'L': + handler.on_num(); + break; + case 'c': + handler.on_chr(); + break; + default: + handler.on_error(); + } +} + +template +FMT_CONSTEXPR float_specs parse_float_type_spec( + const basic_format_specs& specs, ErrorHandler&& eh = {}) { + auto result = float_specs(); + result.showpoint = specs.alt; + switch (specs.type) { + case 0: + result.format = float_format::general; + result.showpoint |= specs.precision > 0; + break; + case 'G': + result.upper = true; + FMT_FALLTHROUGH; + case 'g': + result.format = float_format::general; + break; + case 'E': + result.upper = true; + FMT_FALLTHROUGH; + case 'e': + result.format = float_format::exp; + result.showpoint |= specs.precision != 0; + break; + case 'F': + result.upper = true; + FMT_FALLTHROUGH; + case 'f': + result.format = float_format::fixed; + result.showpoint |= specs.precision != 0; + break; + case 'A': + result.upper = true; + FMT_FALLTHROUGH; + case 'a': + result.format = float_format::hex; + break; +#ifdef FMT_DEPRECATED_N_SPECIFIER + case 'n': +#endif + case 'L': + result.locale = true; + break; + default: + eh.on_error("invalid type specifier"); + break; + } + return result; +} + +template +FMT_CONSTEXPR void handle_char_specs(const basic_format_specs* specs, + Handler&& handler) { + if (!specs) return handler.on_char(); + if (specs->type && specs->type != 'c') return handler.on_int(); + if (specs->align == align::numeric || specs->sign != sign::none || specs->alt) + handler.on_error("invalid format specifier for char"); + handler.on_char(); +} + +template +FMT_CONSTEXPR void handle_cstring_type_spec(Char spec, Handler&& handler) { + if (spec == 0 || spec == 's') + handler.on_string(); + else if (spec == 'p') + handler.on_pointer(); + else + handler.on_error("invalid type specifier"); +} + +template +FMT_CONSTEXPR void check_string_type_spec(Char spec, ErrorHandler&& eh) { + if (spec != 0 && spec != 's') eh.on_error("invalid type specifier"); +} + +template +FMT_CONSTEXPR void check_pointer_type_spec(Char spec, ErrorHandler&& eh) { + if (spec != 0 && spec != 'p') eh.on_error("invalid type specifier"); +} + +template class int_type_checker : private ErrorHandler { + public: + FMT_CONSTEXPR explicit int_type_checker(ErrorHandler eh) : ErrorHandler(eh) {} + + FMT_CONSTEXPR void on_dec() {} + FMT_CONSTEXPR void on_hex() {} + FMT_CONSTEXPR void on_bin() {} + FMT_CONSTEXPR void on_oct() {} + FMT_CONSTEXPR void on_num() {} + FMT_CONSTEXPR void on_chr() {} + + FMT_CONSTEXPR void on_error() { + ErrorHandler::on_error("invalid type specifier"); + } +}; + +template +class char_specs_checker : public ErrorHandler { + private: + char type_; + + public: + FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh) + : ErrorHandler(eh), type_(type) {} + + FMT_CONSTEXPR void on_int() { + handle_int_type_spec(type_, int_type_checker(*this)); + } + FMT_CONSTEXPR void on_char() {} +}; + +template +class cstring_type_checker : public ErrorHandler { + public: + FMT_CONSTEXPR explicit cstring_type_checker(ErrorHandler eh) + : ErrorHandler(eh) {} + + FMT_CONSTEXPR void on_string() {} + FMT_CONSTEXPR void on_pointer() {} +}; + +template +FMT_NOINLINE OutputIt fill(OutputIt it, size_t n, const fill_t& fill) { + auto fill_size = fill.size(); + if (fill_size == 1) return std::fill_n(it, n, fill[0]); + for (size_t i = 0; i < n; ++i) it = std::copy_n(fill.data(), fill_size, it); + return it; +} + +// Writes the output of f, padded according to format specifications in specs. +// size: output size in code units. +// width: output display width in (terminal) column positions. +template +inline OutputIt write_padded(OutputIt out, + const basic_format_specs& specs, size_t size, + size_t width, const F& f) { + static_assert(align == align::left || align == align::right, ""); + unsigned spec_width = to_unsigned(specs.width); + size_t padding = spec_width > width ? spec_width - width : 0; + auto* shifts = align == align::left ? data::left_padding_shifts + : data::right_padding_shifts; + size_t left_padding = padding >> shifts[specs.align]; + auto it = reserve(out, size + padding * specs.fill.size()); + it = fill(it, left_padding, specs.fill); + it = f(it); + it = fill(it, padding - left_padding, specs.fill); + return base_iterator(out, it); +} + +template +inline OutputIt write_padded(OutputIt out, + const basic_format_specs& specs, size_t size, + const F& f) { + return write_padded(out, specs, size, size, f); +} + +template +OutputIt write_bytes(OutputIt out, string_view bytes, + const basic_format_specs& specs) { + using iterator = remove_reference_t; + return write_padded(out, specs, bytes.size(), [bytes](iterator it) { + const char* data = bytes.data(); + return copy_str(data, data + bytes.size(), it); + }); +} + +// Data for write_int that doesn't depend on output iterator type. It is used to +// avoid template code bloat. +template struct write_int_data { + size_t size; + size_t padding; + + write_int_data(int num_digits, string_view prefix, + const basic_format_specs& specs) + : size(prefix.size() + to_unsigned(num_digits)), padding(0) { + if (specs.align == align::numeric) { + auto width = to_unsigned(specs.width); + if (width > size) { + padding = width - size; + size = width; + } + } else if (specs.precision > num_digits) { + size = prefix.size() + to_unsigned(specs.precision); + padding = to_unsigned(specs.precision - num_digits); + } + } +}; + +// Writes an integer in the format +// +// where are written by f(it). +template +OutputIt write_int(OutputIt out, int num_digits, string_view prefix, + const basic_format_specs& specs, F f) { + auto data = write_int_data(num_digits, prefix, specs); + using iterator = remove_reference_t; + return write_padded(out, specs, data.size, [=](iterator it) { + if (prefix.size() != 0) + it = copy_str(prefix.begin(), prefix.end(), it); + it = std::fill_n(it, data.padding, static_cast('0')); + return f(it); + }); +} + +template +OutputIt write(OutputIt out, basic_string_view s, + const basic_format_specs& specs) { + auto data = s.data(); + auto size = s.size(); + if (specs.precision >= 0 && to_unsigned(specs.precision) < size) + size = code_point_index(s, to_unsigned(specs.precision)); + auto width = specs.width != 0 + ? count_code_points(basic_string_view(data, size)) + : 0; + using iterator = remove_reference_t; + return write_padded(out, specs, size, width, [=](iterator it) { + return copy_str(data, data + size, it); + }); +} + +// The handle_int_type_spec handler that writes an integer. +template struct int_writer { + OutputIt out; + locale_ref locale; + const basic_format_specs& specs; + UInt abs_value; + char prefix[4]; + unsigned prefix_size; + + using iterator = + remove_reference_t(), 0))>; + + string_view get_prefix() const { return string_view(prefix, prefix_size); } + + template + int_writer(OutputIt output, locale_ref loc, Int value, + const basic_format_specs& s) + : out(output), + locale(loc), + specs(s), + abs_value(static_cast(value)), + prefix_size(0) { + static_assert(std::is_same, UInt>::value, ""); + if (is_negative(value)) { + prefix[0] = '-'; + ++prefix_size; + abs_value = 0 - abs_value; + } else if (specs.sign != sign::none && specs.sign != sign::minus) { + prefix[0] = specs.sign == sign::plus ? '+' : ' '; + ++prefix_size; + } + } + + void on_dec() { + auto num_digits = count_digits(abs_value); + out = write_int( + out, num_digits, get_prefix(), specs, [this, num_digits](iterator it) { + return format_decimal(it, abs_value, num_digits).end; + }); + } + + void on_hex() { + if (specs.alt) { + prefix[prefix_size++] = '0'; + prefix[prefix_size++] = specs.type; + } + int num_digits = count_digits<4>(abs_value); + out = write_int(out, num_digits, get_prefix(), specs, + [this, num_digits](iterator it) { + return format_uint<4, Char>(it, abs_value, num_digits, + specs.type != 'x'); + }); + } + + void on_bin() { + if (specs.alt) { + prefix[prefix_size++] = '0'; + prefix[prefix_size++] = static_cast(specs.type); + } + int num_digits = count_digits<1>(abs_value); + out = write_int(out, num_digits, get_prefix(), specs, + [this, num_digits](iterator it) { + return format_uint<1, Char>(it, abs_value, num_digits); + }); + } + + void on_oct() { + int num_digits = count_digits<3>(abs_value); + if (specs.alt && specs.precision <= num_digits && abs_value != 0) { + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + prefix[prefix_size++] = '0'; + } + out = write_int(out, num_digits, get_prefix(), specs, + [this, num_digits](iterator it) { + return format_uint<3, Char>(it, abs_value, num_digits); + }); + } + + enum { sep_size = 1 }; + + void on_num() { + std::string groups = grouping(locale); + if (groups.empty()) return on_dec(); + auto sep = thousands_sep(locale); + if (!sep) return on_dec(); + int num_digits = count_digits(abs_value); + int size = num_digits, n = num_digits; + std::string::const_iterator group = groups.cbegin(); + while (group != groups.cend() && n > *group && *group > 0 && + *group != max_value()) { + size += sep_size; + n -= *group; + ++group; + } + if (group == groups.cend()) size += sep_size * ((n - 1) / groups.back()); + char digits[40]; + format_decimal(digits, abs_value, num_digits); + basic_memory_buffer buffer; + size += static_cast(prefix_size); + const auto usize = to_unsigned(size); + buffer.resize(usize); + basic_string_view s(&sep, sep_size); + // Index of a decimal digit with the least significant digit having index 0. + int digit_index = 0; + group = groups.cbegin(); + auto p = buffer.data() + size; + for (int i = num_digits - 1; i >= 0; --i) { + *--p = static_cast(digits[i]); + if (*group <= 0 || ++digit_index % *group != 0 || + *group == max_value()) + continue; + if (group + 1 != groups.cend()) { + digit_index = 0; + ++group; + } + p -= s.size(); + std::uninitialized_copy(s.data(), s.data() + s.size(), + make_checked(p, s.size())); + } + if (prefix_size != 0) p[-1] = static_cast('-'); + auto data = buffer.data(); + out = write_padded( + out, specs, usize, usize, + [=](iterator it) { return copy_str(data, data + size, it); }); + } + + void on_chr() { *out++ = static_cast(abs_value); } + + FMT_NORETURN void on_error() { + FMT_THROW(format_error("invalid type specifier")); + } +}; + +template +OutputIt write_nonfinite(OutputIt out, bool isinf, + const basic_format_specs& specs, + const float_specs& fspecs) { + auto str = + isinf ? (fspecs.upper ? "INF" : "inf") : (fspecs.upper ? "NAN" : "nan"); + constexpr size_t str_size = 3; + auto sign = fspecs.sign; + auto size = str_size + (sign ? 1 : 0); + using iterator = remove_reference_t; + return write_padded(out, specs, size, [=](iterator it) { + if (sign) *it++ = static_cast(data::signs[sign]); + return copy_str(str, str + str_size, it); + }); +} + +// A decimal floating-point number significand * pow(10, exp). +struct big_decimal_fp { + const char* significand; + int significand_size; + int exp; +}; + +template +OutputIt write_float(OutputIt out, const big_decimal_fp& fp, float_specs specs, + Char decimal_point) { + const char* digits = fp.significand; + const Char zero = static_cast('0'); + + int output_exp = fp.exp + fp.significand_size - 1; + auto use_exp_format = [=]() { + if (specs.format == float_format::exp) return true; + if (specs.format != float_format::general) return false; + // Format numbers with the exponent in [exp_lower, exp_upper) using + // the fixed notation, e.g. prefer 0.0001 to 1e-04. + const int exp_lower = -4, exp_upper = 16; + return output_exp < exp_lower || + output_exp >= (specs.precision > 0 ? specs.precision : exp_upper); + }; + if (use_exp_format()) { + // Insert a decimal point after the first digit and add an exponent. + *out++ = static_cast(*digits); + int num_zeros = specs.precision - fp.significand_size; + if (fp.significand_size > 1 || specs.showpoint) *out++ = decimal_point; + out = copy_str(digits + 1, digits + fp.significand_size, out); + if (num_zeros > 0 && specs.showpoint) + out = std::fill_n(out, num_zeros, zero); + *out++ = static_cast(specs.upper ? 'E' : 'e'); + return write_exponent(output_exp, out); + } + + int exp = fp.exp + fp.significand_size; + if (fp.significand_size <= exp) { + // 1234e7 -> 12340000000[.0+] + out = copy_str(digits, digits + fp.significand_size, out); + out = std::fill_n(out, exp - fp.significand_size, zero); + if (specs.showpoint) { + *out++ = decimal_point; + int num_zeros = specs.precision - exp; + if (num_zeros <= 0) { + if (specs.format != float_format::fixed) *out++ = zero; + return out; + } +#ifdef FMT_FUZZ + if (num_zeros > 5000) + throw std::runtime_error("fuzz mode - avoiding excessive cpu use"); +#endif + out = std::fill_n(out, num_zeros, zero); + } + } else if (exp > 0) { + // 1234e-2 -> 12.34[0+] + out = copy_str(digits, digits + exp, out); + if (!specs.showpoint) { + if (fp.significand_size != exp) *out++ = decimal_point; + return copy_str(digits + exp, digits + fp.significand_size, out); + } + *out++ = decimal_point; + out = copy_str(digits + exp, digits + fp.significand_size, out); + // Add trailing zeros. + if (specs.precision > fp.significand_size) + out = std::fill_n(out, specs.precision - fp.significand_size, zero); + } else { + // 1234e-6 -> 0.001234 + *out++ = zero; + int num_zeros = -exp; + if (fp.significand_size == 0 && specs.precision >= 0 && + specs.precision < num_zeros) { + num_zeros = specs.precision; + } + if (num_zeros != 0 || fp.significand_size != 0 || specs.showpoint) { + *out++ = decimal_point; + out = std::fill_n(out, num_zeros, zero); + out = copy_str(digits, digits + fp.significand_size, out); + } + } + return out; +} + +// The number is given as v = significand * pow(10, exp). +template +OutputIt write_float(OutputIt out, const buffer& significand, int exp, + const basic_format_specs& specs, float_specs fspecs, + Char decimal_point) { + auto fp = big_decimal_fp{significand.data(), + static_cast(significand.size()), exp}; + auto size = + write_float(counting_iterator(), fp, fspecs, decimal_point).count(); + size += fspecs.sign ? 1 : 0; + using iterator = remove_reference_t; + return write_padded(out, specs, size, [&](iterator it) { + if (fspecs.sign) *it++ = static_cast(data::signs[fspecs.sign]); + return write_float(it, fp, fspecs, decimal_point); + }); +} + +template ::value)> +OutputIt write(OutputIt out, T value, basic_format_specs specs, + locale_ref loc = {}) { + if (const_check(!is_supported_floating_point(value))) return out; + float_specs fspecs = parse_float_type_spec(specs); + fspecs.sign = specs.sign; + if (std::signbit(value)) { // value < 0 is false for NaN so use signbit. + fspecs.sign = sign::minus; + value = -value; + } else if (fspecs.sign == sign::minus) { + fspecs.sign = sign::none; + } + + if (!std::isfinite(value)) + return write_nonfinite(out, std::isinf(value), specs, fspecs); + + if (specs.align == align::numeric && fspecs.sign) { + auto it = reserve(out, 1); + *it++ = static_cast(data::signs[fspecs.sign]); + out = base_iterator(out, it); + fspecs.sign = sign::none; + if (specs.width != 0) --specs.width; + } + + memory_buffer buffer; + if (fspecs.format == float_format::hex) { + if (fspecs.sign) buffer.push_back(data::signs[fspecs.sign]); + snprintf_float(promote_float(value), specs.precision, fspecs, buffer); + return write_bytes(out, {buffer.data(), buffer.size()}, specs); + } + int precision = specs.precision >= 0 || !specs.type ? specs.precision : 6; + if (fspecs.format == float_format::exp) { + if (precision == max_value()) + FMT_THROW(format_error("number is too big")); + else + ++precision; + } + if (const_check(std::is_same())) fspecs.binary32 = true; + fspecs.use_grisu = is_fast_float(); + int exp = format_float(promote_float(value), precision, fspecs, buffer); + fspecs.precision = precision; + Char point = + fspecs.locale ? decimal_point(loc) : static_cast('.'); + return write_float(out, buffer, exp, specs, fspecs, point); +} + +template < + typename Char, typename OutputIt, typename T, + FMT_ENABLE_IF(std::is_floating_point::value&& is_fast_float::value)> +OutputIt write(OutputIt out, T value) { + if (const_check(!is_supported_floating_point(value))) return out; + auto fspecs = float_specs(); + if (std::signbit(value)) { // value < 0 is false for NaN so use signbit. + fspecs.sign = sign::minus; + value = -value; + } + + auto specs = basic_format_specs(); + if (!std::isfinite(value)) + return write_nonfinite(out, std::isinf(value), specs, fspecs); + + using type = conditional_t::value, double, T>; + auto dec = dragonbox::to_decimal(static_cast(value)); + memory_buffer buf; + write(buffer_appender(buf), dec.significand); + return write_float(out, buf, dec.exponent, specs, fspecs, + static_cast('.')); +} + +template ::value && + !is_fast_float::value)> +inline OutputIt write(OutputIt out, T value) { + return write(out, value, basic_format_specs()); +} + +template +OutputIt write_char(OutputIt out, Char value, + const basic_format_specs& specs) { + using iterator = remove_reference_t; + return write_padded(out, specs, 1, [=](iterator it) { + *it++ = value; + return it; + }); +} + +template +OutputIt write_ptr(OutputIt out, UIntPtr value, + const basic_format_specs* specs) { + int num_digits = count_digits<4>(value); + auto size = to_unsigned(num_digits) + size_t(2); + using iterator = remove_reference_t; + auto write = [=](iterator it) { + *it++ = static_cast('0'); + *it++ = static_cast('x'); + return format_uint<4, Char>(it, value, num_digits); + }; + return specs ? write_padded(out, *specs, size, write) + : base_iterator(out, write(reserve(out, size))); +} + +template struct is_integral : std::is_integral {}; +template <> struct is_integral : std::true_type {}; +template <> struct is_integral : std::true_type {}; + +template +OutputIt write(OutputIt out, monostate) { + FMT_ASSERT(false, ""); + return out; +} + +template ::value)> +OutputIt write(OutputIt out, string_view value) { + auto it = reserve(out, value.size()); + it = copy_str(value.begin(), value.end(), it); + return base_iterator(out, it); +} + +template +OutputIt write(OutputIt out, basic_string_view value) { + auto it = reserve(out, value.size()); + it = std::copy(value.begin(), value.end(), it); + return base_iterator(out, it); +} + +template +buffer_appender write(buffer_appender out, + basic_string_view value) { + get_container(out).append(value.begin(), value.end()); + return out; +} + +template ::value && + !std::is_same::value && + !std::is_same::value)> +OutputIt write(OutputIt out, T value) { + auto abs_value = static_cast>(value); + bool negative = is_negative(value); + // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer. + if (negative) abs_value = ~abs_value + 1; + int num_digits = count_digits(abs_value); + auto size = (negative ? 1 : 0) + static_cast(num_digits); + auto it = reserve(out, size); + if (auto ptr = to_pointer(it, size)) { + if (negative) *ptr++ = static_cast('-'); + format_decimal(ptr, abs_value, num_digits); + return out; + } + if (negative) *it++ = static_cast('-'); + it = format_decimal(it, abs_value, num_digits).end; + return base_iterator(out, it); +} + +template +OutputIt write(OutputIt out, bool value) { + return write(out, string_view(value ? "true" : "false")); +} + +template +OutputIt write(OutputIt out, Char value) { + auto it = reserve(out, 1); + *it++ = value; + return base_iterator(out, it); +} + +template +OutputIt write(OutputIt out, const Char* value) { + if (!value) { + FMT_THROW(format_error("string pointer is null")); + } else { + auto length = std::char_traits::length(value); + out = write(out, basic_string_view(value, length)); + } + return out; +} + +template +OutputIt write(OutputIt out, const void* value) { + return write_ptr(out, to_uintptr(value), nullptr); +} + +template +auto write(OutputIt out, const T& value) -> typename std::enable_if< + mapped_type_constant>::value == + type::custom_type, + OutputIt>::type { + using context_type = basic_format_context; + using formatter_type = + conditional_t::value, + typename context_type::template formatter_type, + fallback_formatter>; + context_type ctx(out, {}, {}); + return formatter_type().format(value, ctx); +} + +// An argument visitor that formats the argument and writes it via the output +// iterator. It's a class and not a generic lambda for compatibility with C++11. +template struct default_arg_formatter { + using context = basic_format_context; + + OutputIt out; + basic_format_args args; + locale_ref loc; + + template OutputIt operator()(T value) { + return write(out, value); + } + + OutputIt operator()(typename basic_format_arg::handle handle) { + basic_format_parse_context parse_ctx({}); + basic_format_context format_ctx(out, args, loc); + handle.format(parse_ctx, format_ctx); + return format_ctx.out(); + } +}; + +template +class arg_formatter_base { + public: + using iterator = OutputIt; + using char_type = Char; + using format_specs = basic_format_specs; + + private: + iterator out_; + locale_ref locale_; + format_specs* specs_; + + // Attempts to reserve space for n extra characters in the output range. + // Returns a pointer to the reserved range or a reference to out_. + auto reserve(size_t n) -> decltype(detail::reserve(out_, n)) { + return detail::reserve(out_, n); + } + + using reserve_iterator = remove_reference_t(), 0))>; + + template void write_int(T value, const format_specs& spec) { + using uint_type = uint32_or_64_or_128_t; + int_writer w(out_, locale_, value, spec); + handle_int_type_spec(spec.type, w); + out_ = w.out; + } + + void write(char value) { + auto&& it = reserve(1); + *it++ = value; + } + + template ::value)> + void write(Ch value) { + out_ = detail::write(out_, value); + } + + void write(string_view value) { + auto&& it = reserve(value.size()); + it = copy_str(value.begin(), value.end(), it); + } + void write(wstring_view value) { + static_assert(std::is_same::value, ""); + auto&& it = reserve(value.size()); + it = std::copy(value.begin(), value.end(), it); + } + + template + void write(const Ch* s, size_t size, const format_specs& specs) { + auto width = specs.width != 0 + ? count_code_points(basic_string_view(s, size)) + : 0; + out_ = write_padded(out_, specs, size, width, [=](reserve_iterator it) { + return copy_str(s, s + size, it); + }); + } + + template + void write(basic_string_view s, const format_specs& specs = {}) { + out_ = detail::write(out_, s, specs); + } + + void write_pointer(const void* p) { + out_ = write_ptr(out_, to_uintptr(p), specs_); + } + + struct char_spec_handler : ErrorHandler { + arg_formatter_base& formatter; + Char value; + + char_spec_handler(arg_formatter_base& f, Char val) + : formatter(f), value(val) {} + + void on_int() { + // char is only formatted as int if there are specs. + formatter.write_int(static_cast(value), *formatter.specs_); + } + void on_char() { + if (formatter.specs_) + formatter.out_ = write_char(formatter.out_, value, *formatter.specs_); + else + formatter.write(value); + } + }; + + struct cstring_spec_handler : error_handler { + arg_formatter_base& formatter; + const Char* value; + + cstring_spec_handler(arg_formatter_base& f, const Char* val) + : formatter(f), value(val) {} + + void on_string() { formatter.write(value); } + void on_pointer() { formatter.write_pointer(value); } + }; + + protected: + iterator out() { return out_; } + format_specs* specs() { return specs_; } + + void write(bool value) { + if (specs_) + write(string_view(value ? "true" : "false"), *specs_); + else + out_ = detail::write(out_, value); + } + + void write(const Char* value) { + if (!value) { + FMT_THROW(format_error("string pointer is null")); + } else { + auto length = std::char_traits::length(value); + basic_string_view sv(value, length); + specs_ ? write(sv, *specs_) : write(sv); + } + } + + public: + arg_formatter_base(OutputIt out, format_specs* s, locale_ref loc) + : out_(out), locale_(loc), specs_(s) {} + + iterator operator()(monostate) { + FMT_ASSERT(false, "invalid argument type"); + return out_; + } + + template ::value)> + FMT_INLINE iterator operator()(T value) { + if (specs_) + write_int(value, *specs_); + else + out_ = detail::write(out_, value); + return out_; + } + + iterator operator()(Char value) { + handle_char_specs(specs_, + char_spec_handler(*this, static_cast(value))); + return out_; + } + + iterator operator()(bool value) { + if (specs_ && specs_->type) return (*this)(value ? 1 : 0); + write(value != 0); + return out_; + } + + template ::value)> + iterator operator()(T value) { + auto specs = specs_ ? *specs_ : format_specs(); + if (const_check(is_supported_floating_point(value))) + out_ = detail::write(out_, value, specs, locale_); + else + FMT_ASSERT(false, "unsupported float argument type"); + return out_; + } + + iterator operator()(const Char* value) { + if (!specs_) return write(value), out_; + handle_cstring_type_spec(specs_->type, cstring_spec_handler(*this, value)); + return out_; + } + + iterator operator()(basic_string_view value) { + if (specs_) { + check_string_type_spec(specs_->type, error_handler()); + write(value, *specs_); + } else { + write(value); + } + return out_; + } + + iterator operator()(const void* value) { + if (specs_) check_pointer_type_spec(specs_->type, error_handler()); + write_pointer(value); + return out_; + } +}; + +template FMT_CONSTEXPR bool is_name_start(Char c) { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; +} + +// Parses the range [begin, end) as an unsigned integer. This function assumes +// that the range is non-empty and the first character is a digit. +template +FMT_CONSTEXPR int parse_nonnegative_int(const Char*& begin, const Char* end, + ErrorHandler&& eh) { + FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); + unsigned value = 0; + // Convert to unsigned to prevent a warning. + constexpr unsigned max_int = max_value(); + unsigned big = max_int / 10; + do { + // Check for overflow. + if (value > big) { + value = max_int + 1; + break; + } + value = value * 10 + unsigned(*begin - '0'); + ++begin; + } while (begin != end && '0' <= *begin && *begin <= '9'); + if (value > max_int) eh.on_error("number is too big"); + return static_cast(value); +} + +template class custom_formatter { + private: + using char_type = typename Context::char_type; + + basic_format_parse_context& parse_ctx_; + Context& ctx_; + + public: + explicit custom_formatter(basic_format_parse_context& parse_ctx, + Context& ctx) + : parse_ctx_(parse_ctx), ctx_(ctx) {} + + bool operator()(typename basic_format_arg::handle h) const { + h.format(parse_ctx_, ctx_); + return true; + } + + template bool operator()(T) const { return false; } +}; + +template +using is_integer = + bool_constant::value && !std::is_same::value && + !std::is_same::value && + !std::is_same::value>; + +template class width_checker { + public: + explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {} + + template ::value)> + FMT_CONSTEXPR unsigned long long operator()(T value) { + if (is_negative(value)) handler_.on_error("negative width"); + return static_cast(value); + } + + template ::value)> + FMT_CONSTEXPR unsigned long long operator()(T) { + handler_.on_error("width is not integer"); + return 0; + } + + private: + ErrorHandler& handler_; +}; + +template class precision_checker { + public: + explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {} + + template ::value)> + FMT_CONSTEXPR unsigned long long operator()(T value) { + if (is_negative(value)) handler_.on_error("negative precision"); + return static_cast(value); + } + + template ::value)> + FMT_CONSTEXPR unsigned long long operator()(T) { + handler_.on_error("precision is not integer"); + return 0; + } + + private: + ErrorHandler& handler_; +}; + +// A format specifier handler that sets fields in basic_format_specs. +template class specs_setter { + public: + explicit FMT_CONSTEXPR specs_setter(basic_format_specs& specs) + : specs_(specs) {} + + FMT_CONSTEXPR specs_setter(const specs_setter& other) + : specs_(other.specs_) {} + + FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; } + FMT_CONSTEXPR void on_fill(basic_string_view fill) { + specs_.fill = fill; + } + FMT_CONSTEXPR void on_plus() { specs_.sign = sign::plus; } + FMT_CONSTEXPR void on_minus() { specs_.sign = sign::minus; } + FMT_CONSTEXPR void on_space() { specs_.sign = sign::space; } + FMT_CONSTEXPR void on_hash() { specs_.alt = true; } + + FMT_CONSTEXPR void on_zero() { + specs_.align = align::numeric; + specs_.fill[0] = Char('0'); + } + + FMT_CONSTEXPR void on_width(int width) { specs_.width = width; } + FMT_CONSTEXPR void on_precision(int precision) { + specs_.precision = precision; + } + FMT_CONSTEXPR void end_precision() {} + + FMT_CONSTEXPR void on_type(Char type) { + specs_.type = static_cast(type); + } + + protected: + basic_format_specs& specs_; +}; + +template class numeric_specs_checker { + public: + FMT_CONSTEXPR numeric_specs_checker(ErrorHandler& eh, detail::type arg_type) + : error_handler_(eh), arg_type_(arg_type) {} + + FMT_CONSTEXPR void require_numeric_argument() { + if (!is_arithmetic_type(arg_type_)) + error_handler_.on_error("format specifier requires numeric argument"); + } + + FMT_CONSTEXPR void check_sign() { + require_numeric_argument(); + if (is_integral_type(arg_type_) && arg_type_ != type::int_type && + arg_type_ != type::long_long_type && arg_type_ != type::char_type) { + error_handler_.on_error("format specifier requires signed argument"); + } + } + + FMT_CONSTEXPR void check_precision() { + if (is_integral_type(arg_type_) || arg_type_ == type::pointer_type) + error_handler_.on_error("precision not allowed for this argument type"); + } + + private: + ErrorHandler& error_handler_; + detail::type arg_type_; +}; + +// A format specifier handler that checks if specifiers are consistent with the +// argument type. +template class specs_checker : public Handler { + private: + numeric_specs_checker checker_; + + // Suppress an MSVC warning about using this in initializer list. + FMT_CONSTEXPR Handler& error_handler() { return *this; } + + public: + FMT_CONSTEXPR specs_checker(const Handler& handler, detail::type arg_type) + : Handler(handler), checker_(error_handler(), arg_type) {} + + FMT_CONSTEXPR specs_checker(const specs_checker& other) + : Handler(other), checker_(error_handler(), other.arg_type_) {} + + FMT_CONSTEXPR void on_align(align_t align) { + if (align == align::numeric) checker_.require_numeric_argument(); + Handler::on_align(align); + } + + FMT_CONSTEXPR void on_plus() { + checker_.check_sign(); + Handler::on_plus(); + } + + FMT_CONSTEXPR void on_minus() { + checker_.check_sign(); + Handler::on_minus(); + } + + FMT_CONSTEXPR void on_space() { + checker_.check_sign(); + Handler::on_space(); + } + + FMT_CONSTEXPR void on_hash() { + checker_.require_numeric_argument(); + Handler::on_hash(); + } + + FMT_CONSTEXPR void on_zero() { + checker_.require_numeric_argument(); + Handler::on_zero(); + } + + FMT_CONSTEXPR void end_precision() { checker_.check_precision(); } +}; + +template