delog-0.1.7/.cargo_vcs_info.json0000644000000001360000000000100121330ustar { "git": { "sha1": "bdb2b12160f24607d147d4654e59e662f0c0a641" }, "path_in_vcs": "" }delog-0.1.7/.github/workflows/ci.yml000064400000000000000000000032711046102023000154410ustar 00000000000000name: CI on: push: branches: [main] pull_request: branches: [main] env: # need atomic CAS, so Cortex-M0/1 are out QEMU_TARGET: thumbv7m-none-eabi jobs: test: strategy: matrix: rust: - stable os: - ubuntu-latest - macos-latest - windows-latest runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.rust }} override: true - name: Check that all crates build without warning run: RUSTFLAGS='--deny warnings' cargo check --all shell: bash - name: Check clippy output (lenient mode) # run: RUSTFLAGS='--deny warnings' cargo clippy --all run: cargo clippy --all shell: bash - name: Run non-QEMU tests run: make non-qemu-tests qemu-test: strategy: matrix: rust: - stable # ubuntu-latest still points to 18.04, which only has QEMU 2 runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.rust }} target: ${{ env.QEMU_TARGET }} override: true - name: Install QEMU (want >= 4) run: | sudo apt-get update -qq >/dev/null sudo apt-get install -qq qemu-system-arm >/dev/null qemu-system-arm --version - name: Build the QEMU tests working-directory: qemu-tests run: make build build-release - name: Run the QEMU tests working-directory: qemu-tests run: make test delog-0.1.7/.gitignore000064400000000000000000000000401046102023000127050ustar 00000000000000**/target **/*.rs.bk Cargo.lock delog-0.1.7/CHANGELOG.md000064400000000000000000000025761046102023000125460ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.1.7] - 2023-08-17 - fix breakage caused by using internal `log` APIs ## [0.1.6] - 2022-08-22 - `std-log` feature to use normal logging for testing etc. @robin-nitrokey ## [0.1.5]- 2022-06-25 - fix incorrect MIT license copyright info ## [0.1.4]- 2022-03-05 - add missing dyn trait, will yank 0.1.3 ## [0.1.3]- 2022-03-05 - Doc-hide some of the macros so our dependees don't have documentation noise - 2021 edition ## [0.1.2]- 2021-04-23 - Allow independent (e.g. smaller) render buffers @conorpp ## [0.1.1]- 2021-04-13 - Bug fixes by @conorpp ## [0.1.0]- 2021-02-27 - Promote existing state (0.1.0-alpha.3) to 0.1.0 ## [0.1.0-alpha.1] - 2020-11-29 - Revamp of logs: only local/gated macros are generated now - Remove optional semihosting dependency, relegate example implementation to QEMU test - Relegate stdout/stderr flushers to example submodule - Simplification of `hex` submodule, removing typenum and implementing all block sizes - Addition of "truncated" hex formats like `hex_fmt`, remove it as dependency instead ## [0.1.0-alpha.1] - 2020-11-28 Test the release process, meditate on the `local_*!` issue. delog-0.1.7/Cargo.lock0000644000000134730000000000100101160ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "console" version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3993e6445baa160675931ec041a5e03ca84b9c6e32a056150d3aa2bdda0a1f45" dependencies = [ "encode_unicode", "lazy_static", "libc", "terminal_size", "winapi", ] [[package]] name = "delog" version = "0.1.7" dependencies = [ "insta", "log", ] [[package]] name = "dtoa" version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0" [[package]] name = "encode_unicode" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" [[package]] name = "insta" version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4a1b21a2971cea49ca4613c0e9fe8225ecaf5de64090fddc6002284726e9244" dependencies = [ "console", "lazy_static", "serde", "serde_json", "serde_yaml", "similar", "uuid", ] [[package]] name = "itoa" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" version = "0.2.93" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9385f66bf6105b241aa65a61cb923ef20efc665cb9f9bb50ac2f0c4b7f378d41" [[package]] name = "linked-hash-map" version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" [[package]] name = "log" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" dependencies = [ "cfg-if", ] [[package]] name = "proc-macro2" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a152013215dca273577e18d2bf00fa862b89b24169fb78c4c95aeb07992c9cec" dependencies = [ "unicode-xid", ] [[package]] name = "quote" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" dependencies = [ "proc-macro2", ] [[package]] name = "ryu" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" [[package]] name = "serde" version = "1.0.125" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "558dc50e1a5a5fa7112ca2ce4effcb321b0300c0d4ccf0776a9f60cd89031171" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.125" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b093b7a2bb58203b5da3056c05b4ec1fed827dcfdb37347a8841695263b3d06d" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "serde_yaml" version = "0.8.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15654ed4ab61726bf918a39cb8d98a2e2995b002387807fa6ba58fdf7f59bb23" dependencies = [ "dtoa", "linked-hash-map", "serde", "yaml-rust", ] [[package]] name = "similar" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ad1d488a557b235fc46dae55512ffbfc429d2482b08b4d9435ab07384ca8aec" [[package]] name = "syn" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48fe99c6bd8b1cc636890bcc071842de909d902c81ac7dab53ba33c421ab8ffb" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "terminal_size" version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86ca8ced750734db02076f44132d802af0b33b09942331f4459dde8636fd2406" dependencies = [ "libc", "winapi", ] [[package]] name = "unicode-xid" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" [[package]] name = "uuid" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "yaml-rust" version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" dependencies = [ "linked-hash-map", ] delog-0.1.7/Cargo.toml0000644000000034100000000000100101270ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "delog" version = "0.1.7" authors = ["Trussed Developers"] description = "Deferred logging, an implementation and extension of Rust's standard logging facade." documentation = "https://docs.rs/delog" readme = "README.md" keywords = [ "log", "logging", "formatting", ] categories = [ "algorithms", "development-tools", "embedded", "no-std", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/trussed-dev/delog" [package.metadata.docs.rs] features = ["example"] targets = [] [dependencies.log] version = "0.4" [dev-dependencies.insta] version = "1.7" [features] example = ["std"] knock-it-off = [ "max_level_off", "release_max_level_off", ] max_level_debug = ["log/max_level_debug"] max_level_error = ["log/max_level_error"] max_level_info = ["log/max_level_info"] max_level_off = ["log/max_level_off"] max_level_trace = ["log/max_level_trace"] max_level_warn = ["log/max_level_warn"] release_max_level_debug = ["log/release_max_level_debug"] release_max_level_error = ["log/release_max_level_error"] release_max_level_info = ["log/release_max_level_info"] release_max_level_off = ["log/release_max_level_off"] release_max_level_trace = ["log/release_max_level_trace"] release_max_level_warn = ["log/release_max_level_warn"] std = [] std-log = [] delog-0.1.7/Cargo.toml.orig000064400000000000000000000026001046102023000136100ustar 00000000000000[package] name = "delog" version = "0.1.7" description = "Deferred logging, an implementation and extension of Rust's standard logging facade." authors = ["Trussed Developers"] license = "Apache-2.0 OR MIT" repository = "https://github.com/trussed-dev/delog" documentation = "https://docs.rs/delog" readme = "README.md" categories = ["algorithms", "development-tools", "embedded", "no-std"] keywords = ["log", "logging", "formatting"] edition = "2021" [package.metadata.docs.rs] features = ["example"] targets = [] [dependencies] log = "0.4" [dev-dependencies] insta = "1.7" [features] example = ["std"] # sole reason for this is to enable `print!` in the example's `Std{err,out}Flusher` std = [] # replace deferred logging with log::log std-log = [] max_level_off = ["log/max_level_off"] max_level_error = ["log/max_level_error"] max_level_warn = ["log/max_level_warn"] max_level_info = ["log/max_level_info"] max_level_debug = ["log/max_level_debug"] max_level_trace = ["log/max_level_trace"] release_max_level_off = ["log/release_max_level_off"] release_max_level_error = ["log/release_max_level_error"] release_max_level_warn = ["log/release_max_level_warn"] release_max_level_info = ["log/release_max_level_info"] release_max_level_debug = ["log/release_max_level_debug"] release_max_level_trace = ["log/release_max_level_trace"] knock-it-off = ["max_level_off", "release_max_level_off"] delog-0.1.7/LICENSE-APACHE000064400000000000000000000251371046102023000126570ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. delog-0.1.7/LICENSE-MIT000064400000000000000000000020631046102023000123600ustar 00000000000000MIT License Copyright (c) 2020 Trussed Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. delog-0.1.7/Makefile000064400000000000000000000005351046102023000123660ustar 00000000000000test: non-qemu-tests qemu-tests non-qemu-tests: simple-tests delog-examples gate-tests simple-tests: cargo test --lib cargo test --doc cargo test --examples .PHONY: delog-examples delog-examples: $(MAKE) -C delog-examples run .PHONY: gate-tests gate-tests: $(MAKE) -C gate-tests .PHONY: qemu-tests qemu-tests: $(MAKE) -C qemu-tests test delog-0.1.7/README.md000064400000000000000000000040011046102023000121750ustar 00000000000000# delog [github](https://github.com/nickray/delog) [docs.rs](https://docs.rs/delog) [build status](https://github.com/nickray/delog/actions?query=branch%3Amain) Deferred logging, an implementation and extension of Rust's standard logging facade. #### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. delog-0.1.7/build.rs000064400000000000000000000005551046102023000123750ustar 00000000000000// use std::env; fn main() -> Result<(), Box> { // println!("cargo:rerun-if-changed=build.rs"); // let target = env::var("TARGET")?; // let cortex_m_dsp = target.starts_with("thumbv7em") || target.starts_with("thumbv8m.main"); // if cortex_m_dsp { // println!("cargo:rustc-cfg=cortex_m_dsp"); // } Ok(()) } delog-0.1.7/examples/hex.rs000064400000000000000000000020501046102023000136700ustar 00000000000000use delog::{hex_str, hexstr}; fn main() { let buf = [1u8, 2, 3, 0xA1, 0xB7, 0xFF, 0x3]; println!("'{}'", hexstr!(&buf)); println!("'{}'", hex_str!(&buf)); println!("'{:4}'", hex_str!(&buf)); println!("'{:<4}'", hex_str!(&buf)); println!("'{:>4}'", hex_str!(&buf)); println!("'{}'", hex_str!(&buf, 2)); println!("'{:02x}'", hex_str!(&buf, 2)); println!("'{}'", hex_str!(&buf, 4)); println!("'{:4}'", hex_str!(&buf, 2)); println!("'{:<4}'", hex_str!(&buf, 2)); println!("'{:>4}'", hex_str!(&buf, 2)); println!("'{}'", hex_str!(&buf[..], 4)); println!("'{}'", hex_str!(&buf, 3)); println!("'{}'", hex_str!(&buf, 2, sep: "|")); println!("'{:2}'", hex_str!(&buf, 2, sep: "|")); println!("'{:3x}'", hex_str!(&buf, 2, sep: "|")); println!("'{:>3x}'", hex_str!(&buf, 2, sep: "|")); println!("'{:<3x}'", hex_str!(&buf, 2, sep: "|")); println!("'{:4}'", hex_str!(&buf, 2, sep: "|")); println!("'{:5x}'", hex_str!(&buf, 2, sep: "|")); println!("'{:6}'", hex_str!(&buf, 2, sep: "|")); } delog-0.1.7/rustfmt.toml000064400000000000000000000000001046102023000133120ustar 00000000000000delog-0.1.7/src/example.rs000064400000000000000000000024441046102023000135170ustar 00000000000000//! An example deferred logger with example flusher. //! //! It is included here for documentation purposes only. //! //! Do ensure that the `example` feature is not active in production! //! //! ``` //! pub struct StderrFlusher {} //! //! impl crate::Flusher for StderrFlusher { //! fn flush(&self, logs: &str) { //! print!("{}", logs); //! } //! } //! //! delog!(Delogger, 256, StderrFlusher); //! static FLUSHER: StderrFlusher = StderrFlusher {}; //! Delogger::init(log::LevelFilter::Info, &STDOUT_FLUSHER).ok(); //! //! warn!("This is a warning"); //! info_now!("This is IMMEDIATE information"); //! info!("twenty-four bits '{}'", delog::hex_str!(&[0xa1u8, 0xfF, 0x03])); //! //! Delogger::flush(); //! ``` // use crate::flushers::StderrFlusher; use crate::render::DefaultRenderer; #[derive(Debug, Default)] /// Flushes logs to stderr. pub struct StderrFlusher {} impl crate::Flusher for StderrFlusher { fn flush(&self, logs: &str) { eprint!("{}", logs); } } #[derive(Debug, Default)] /// Flushes logs to stdout. pub struct StdoutFlusher {} impl crate::Flusher for StdoutFlusher { fn flush(&self, logs: &str) { print!("{}", logs); } } crate::delog!(Delogger, 4096, StderrFlusher, renderer: DefaultRenderer); // #[macro_export] // crate::generate_macros!(); delog-0.1.7/src/hex.rs000064400000000000000000000233071046102023000126510ustar 00000000000000//! Convenient `Display` and other traits for binary data. //! //! Standard Rust uses the `fmt::UpperHex` and `LowerHex` traits to implement hexadecimal //! representations for use in format strings. For instance, //! `format_args!("{:02X?}", &[7, 0xA1, 0xFF])` produces the string `"[07, A1, FF]"`. //! //! ``` //! assert_eq!(format!("{:02X?}", [7u8, 0xA1, 0xFF].as_ref()), "[07, A1, FF]"); //! ``` //! //! However, this only works for the `Debug` trait, not `Display`; needs extra dancing //! to pad with leading zeros, and is not very compact when debugging binary data formats. //! //! The idea of this module is to generate newtypes around byte arrays/slices, and implement the `fmt` traits on these. //! In release builds, this is all compiled out and translates to direct instructions for the formatting machinery. //! //! The ide to implement truncated outputs comes from the `hex_fmt` library, which we refer to //! for additional newtypes that can be used. //! //! ``` //! use delog::{hex_str, hexstr}; //! //! let data = &[7u8, 0xA1, 255, 0xC7]; //! //! assert_eq!(format!("{}", hexstr!(data)), "07A1FFC7"); //! assert_eq!(format!("{:x}", hexstr!(data)), "07a1ffc7"); //! assert_eq!(format!("{:2x}", hex_str!(data)), "07..c7"); //! assert_eq!(format!("{:<3x}", hex_str!(data)), "07 a1 ff.."); //! assert_eq!(format!("{:>3x}", hex_str!(data)), "..a1 ff c7"); //! assert_eq!(format!("{}", hex_str!(data, 2)), "07A1 FFC7"); //! assert_eq!(format!("{:<3}", hex_str!(data, sep: "|")), "07|A1|FF.."); //! ``` use core::fmt; use core::marker::PhantomData; ///// re-export from `hex_fmt` ///// //pub use hex_fmt::HexFmt; ///// re-export from `hex_fmt` ///// //pub use hex_fmt::HexList; /// A type that specifies an unsigned integer. /// /// We use this instead of `typenum` as the latter currently lacks /// a mapping from `usize` to the associated type. pub trait Unsigned { /// The actual number. const N: usize; } /// Sorry little replacement for the missing int to Unsigned type map in `typenum`. #[macro_export] #[doc(hidden)] macro_rules! typeint { ($name:ident, $n:expr) => { /// A type that represents the integer `N`. pub struct $name; impl $crate::hex::Unsigned for $name { const N: usize = $n; } }; } /// A type that represents the integer `1`. pub struct U1; impl Unsigned for U1 { const N: usize = 1; } // /// A type representing the number 1. // pub struct U1 {} // impl Unsigned for U1 { // const N: usize = 1; // } /// A type that specifies a separator str. pub trait Separator { /// The actual separator str. const SEPARATOR: &'static str; } #[macro_export] #[doc(hidden)] macro_rules! typesep { ($name:ident, $s:expr) => { /// A type that represents the integer `N`. pub struct $name; impl $crate::hex::Separator for $name { const SEPARATOR: &'static str = $s; } }; } // /// New approach. // pub trait HexStrTrait { // const BYTES_PER_BLOCK: usize; // const SEPARATOR: &'static str; // fn bytes(&self) -> &[u8]; // } /// Zero-sized wrapper newtype, allowing grouping bytes in blocks of N hexadecimals /// during formatting. /// /// Use the method with the same name to construct this from your byte array or slice, /// or preferrably the `hex_str!` or `hexstr!` macro. pub struct HexStr<'a, T: ?Sized, U, S> where U: Unsigned, S: Separator, { /// The value to be formatted. pub value: &'a T, _bytes_per_block: PhantomData, _separator: PhantomData, } #[macro_export] /// Compactly format byte arrays and slices as hexadecimals. /// /// The second parameter refers to the number of bytes in a block (separated by spaces). /// /// ``` /// use delog::hex_str; /// let four_bytes = &[7u8, 0xA1, 255, 0xC7]; /// assert_eq!(format!("{:x}", hex_str!(four_bytes)), "07 a1 ff c7"); /// assert_eq!(format!("{}", hex_str!(four_bytes, 2)), "07A1 FFC7"); /// assert_eq!(format!("{}", hex_str!(four_bytes, 2, sep: "|")), "07A1|FFC7"); /// assert_eq!(format!("{}", hex_str!(four_bytes, 3)), "07A1FF C7"); /// ``` macro_rules! hex_str { ($array:expr) => { $crate::hex_str!($array, 1, sep: " ") }; ($array:expr, sep: $separator:expr) => { $crate::hex_str!($array, 1, sep: $separator) }; ($array:expr, $n:tt) => { $crate::hex_str!($array, $n, sep: " ") }; ($array:expr, $n:tt, sep: $separator:expr) => {{ $crate::typesep!(Separator, $separator); $crate::typeint!(Number, $n); $crate::hex::HexStr::<_, Number, Separator>($array) }}; } #[macro_export] /// More compactly format byte arrays and slices as hexadecimals. /// /// ``` /// use delog::hexstr; /// let four_bytes = &[7u8, 0xA1, 255, 0xC7]; /// assert_eq!(format!("{}", hexstr!(four_bytes)), "07A1FFC7"); /// assert_eq!(format!("{:x}", hexstr!(four_bytes)), "07a1ffc7"); /// ``` macro_rules! hexstr { ($array:expr) => { $crate::hex_str!($array, sep: "") } } #[allow(non_snake_case)] /// Explicitly construct a newtype to format with. /// /// The first generic parameter specifies the block size in bytes, the second parameter /// the separator string. /// /// This function is just here for documentation of what the `hex_str!` macro /// does internally (using the undocumented `typeint!` and `typesep!` macros). /// /// ``` /// use delog::hex::{HexStr, Separator, Unsigned}; /// /// // typeint!(U3, 3); /// struct U3 {} /// impl Unsigned for U3 { /// const N: usize = 3; /// } /// /// // typesep!(Pipe, "|"); /// struct Pipe {} /// impl Separator for Pipe { /// const SEPARATOR: &'static str = "|"; /// } /// /// let four_bytes = &[7u8, 0xA1, 255, 0xC7]; /// let hex_str = HexStr::<_, U3, Pipe>(four_bytes); /// /// assert_eq!(format!("{}", hex_str), "07A1FF|C7"); /// ``` pub fn HexStr(value: &T) -> HexStr { HexStr { value, _bytes_per_block: PhantomData, _separator: PhantomData, } } impl fmt::Debug for HexStr<'_, T, U, S> where T: AsRef<[u8]>, U: Unsigned, S: Separator, { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::Display::fmt(self, f) } } impl fmt::Display for HexStr<'_, T, U, S> where T: AsRef<[u8]>, U: Unsigned, S: Separator, { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::UpperHex::fmt(self, f) } } macro_rules! implement { ($Trait:ident, $padded_formatter:expr) => { impl<'a, T: ?Sized, U, S> fmt::$Trait for HexStr<'a, T, U, S> where T: AsRef<[u8]>, U: Unsigned, S: Separator, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { use core::fmt::{self, Alignment::*}; let max_bytes = f.width().unwrap_or(usize::MAX); let bytes = self.value.as_ref(); #[inline] fn nontruncated_fmt( bytes: &[u8], f: &mut fmt::Formatter<'_>, chunk_size: usize, separator: &str, ) -> Result<(), fmt::Error> { let mut first = true; for entry in bytes.chunks(chunk_size) { if first { first = false; } else { f.write_str(separator)?; } for byte in entry.iter() { write!(f, $padded_formatter, byte)?; } } Ok(()) } // const ELLIPSIS: &str = "…"; const ELLIPSIS: &str = ".."; let chunk_size = U::N; let separator = S::SEPARATOR; if bytes.len() <= max_bytes { nontruncated_fmt(bytes, f, chunk_size, separator) } else { let align = f.align().unwrap_or(Center); let (left, right) = match align { Left => (max_bytes, 0), Center => (max_bytes - max_bytes / 2, max_bytes / 2), Right => (0, max_bytes), }; nontruncated_fmt(&bytes[..left], f, chunk_size, separator)?; // if left > 0 { // f.write_str(separator)?; // } f.write_str(ELLIPSIS)?; // if right > 0 { // f.write_str(separator)?; // } nontruncated_fmt(&bytes[bytes.len() - right..], f, chunk_size, separator)?; Ok(()) } } } }; } implement!(LowerHex, "{:02x}"); implement!(UpperHex, "{:02X}"); #[cfg(test)] mod test { use super::*; #[test] fn test_hex_str() { let buf = [1u8, 2, 3, 0xA1, 0xB7, 0xFF, 0x3]; insta::assert_debug_snapshot!(format_args!("'{}'", hex_str!(&buf))); insta::assert_debug_snapshot!(format_args!("'{}'", hex_str!(&buf, 2))); insta::assert_debug_snapshot!(format_args!("'{:x}'", hex_str!(&buf, 2))); insta::assert_debug_snapshot!(format_args!("'{}'", hex_str!(&buf, 4))); insta::assert_debug_snapshot!(format_args!("'{}'", hex_str!(&buf[..], 4))); insta::assert_debug_snapshot!(format_args!("'{}'", hex_str!(&buf, 4))); insta::assert_debug_snapshot!(format_args!("'{}'", hex_str!(&buf, 4))); } #[test] fn test_custom_hex_str() { let buf = [1u8, 2, 3, 0xA1, 0xB7, 0xFF, 0x3]; typeint!(U3, 3); typesep!(Space, " "); insta::assert_debug_snapshot!(format_args!("'{:X}'", HexStr::<_, U3, Space>(&buf),)); } } delog-0.1.7/src/lib.rs000064400000000000000000000217651046102023000126410ustar 00000000000000//! # Compile-time configurable deferred logging (for `printf()`-debugging *aka* tracing) //! //! This is an implementation of the `log::Log` trait, suitable for use //! in both embedded and desktop environments. //! //! It has two main goals: //! - logs are stored in a circular static memory buffer, so that logging is "zero-cost in the inner //! loop" (apart from the formatting), with deferred actual I/O later via flushing. //! - compile-time log level settings for applications with multiple library components; //! inactive log levels of libraries are completely compiled out. //! //! Moreover, setting the kill switch feature flag `knock-it-off`, any and all traces of logging //! are removed from the final binary. //! //! ## Usage and defaults //! //! > *"Global settings subtractive (default all), local settings additive (default none) but with kill-switch."* //! //! From `log`, we inherit: //! - static global filters, default `LevelFilter::Trace` (i.e., everything), set via `delog` or //! `log` feature flags (multiple settings result in the most restrictive filter) //! - dynamic global filter, initialized in the "init"/"init_default" constructors of the //! macro-generated structs implementing our `Delogger` trait. This can be changed by calls to //! the global `set_max_level` function in `log`. //! //! Libraries that use the logging macros from `log` are governed by the more restrictive of these two settings. //! //! On the other hand, a library that uses the `delog::generate_macros!()` macro gains macros `info!`, `warn!`, etc., //! which, by default, do nothing, and are completely optimized out. //! //! If such a libray itself defines a feature `log-all` that is active, then logging calls with these macros are passed through //! and goverend by the global filters. Such a library can also define a feature such as //! `log-info`, which activates *exactly* the info-level logs; it is up to the library to define //! logic such as "log-info implies log-warn". There is a kill-switch: if the library defines a //! feature `log-none`, and some intermediate library activates one of the additive `log-*` //! features, setting `log-none` completely turns off logging for this library. //! //! ## Background //! //! Compared to existing approaches such as `ufmt`, `cortex-m-funnel` and `defmt`, //! we pursue different values and requirements, namely: //! //! - **compatibility with the standard `core::fmt` traits and the standard `log` library API**. //! This means that, while libraries may "upgrade" their logging capabilities by using `delog` //! as drop-in replacement for their logging calls (see below), any existing library that already //! uses `log` is compatible. This, for our use cases, is a huge win, as opposed to using up "weirdness //! budget" and requiring custom tooling for something that is often trivial, throw-away, simple logging. //! - it follows that one can easily drop a `trace!("{:?}", &suspicious_object)` call at any time for //! any object that has a (possibly automatically derived) `Debug` trait implementation – without //! passing around structures and keeping on top of lifetimes. //! - deferred logging: This is a typical "shared memory" logger, calls to `info!` etc. //! are not directly sent to their final output, but instead are stored in a circular buffer //! that is "drained" by calling `flush` on the logger at a convenient moment, for instance //! in an idle loop. //! - immediate mode logging: Sometimes one wants to bypass the deferred flushing of logs, //! this is possible using either the little-known `target` argument to `info!` and friends //! with "!" as parameter, or using the additional `immediate_info!` and friends macros. //! - ability to set log levels *per library, at compile-time*. This can be easily retro-fitted //! on existing `log`-based libraries, by adding the requisite features in `Cargo.toml` and //! replacing `log` with `delog` (see `gate-tests` for examples of this). //! - the outcome is that one can leave useful logging calls in the library code, only to activate //! them in targeted ways at build time, exactly as needed. //! - helper macros to easily output binary byte arrays and slices in hexadecimal representations, //! which wrap the data in newtypes with custom `fmt::UpperHex` etc. implementations. //! //! **Non-goals**: //! //! - ultimate speed or code size: Our intention are "normal" logs, not the use of logging/tracing to //! for stream binary data to the host. While admittedly the `core::fmt`-ing facilities are not as //! efficient as one might hope, in our use cases we have sufficient flash and RAM to use these (and //! some hope that, someday, eventually, maybe, the formatting machinery will be revisited and //! improved at the root level, namely the language itself.) //! //! That said, we believe there is opportunity to extend `delog` in the `defmt` direction by //! using, e.g., the `fmt::Binary` trait, newtypes and sentinel values to embed raw binary //! representations of data in time-critical situations without formatting, deferring //! the extraction and actual formatting to some host-side mechanism. //! //! ## Features //! The `flushers` and `semihosting` features mostly exist to share code within the examples, //! including the `example` feature. Without them, dependencies are quite minimal, and compilation fast. //! //! The `fallible` and `immediate` features (default on) activate the `try_*!` and `*_now!` macros, respectively. //! //! ## Warning //! The current circular buffer implementation (v0.1.0) is definitely unsound on desktop. //! For embedded use, atomics are required (so no Cortex-M0/M1, and no plans to support non-atomic //! platforms, which are likely to also be too resource-constrained to support the bloat inherent //! in `core::fmt`). While we think the implemented circular buffer algorithm works for the "nested interrupt" //! setup of NVICs, it has not been tested much. //! The hope is that the worst case scenario is some slightly messed up log outputs. //! //! ## Outlook //! We plan to iterate towards a v0.2.0 soon, making use of a separate "flusher" for the //! "immediate" logging path. For instance, when logging via serial-over-USB, one might want immediate //! logs to pend a separate RTIC interrupt handler that blocks until the logs are pushed and read //! (allowing one to debug the boot process of a firmware), or one might want to just write to RTT //! (or even semihosting xD) for these, during development. //! #![deny(missing_docs)] #![cfg_attr(not(any(feature = "std", test)), no_std)] use core::fmt; pub use log; pub use log::{Level, LevelFilter, Record}; #[cfg(feature = "example")] pub mod example; pub mod hex; mod logger; mod macros; pub mod render; pub use logger::{ dequeue, enqueue, try_enqueue, Delogger, State, Statistics, TryLog, TryLogWithStatistics, }; /// A way to pass on logs, user supplied. /// /// In embedded, this is intended to pend an interrupt /// to send the logs off via (USB) serial, semihosting, or similar. /// /// On PC, typical implemenation will just println! or eprintln! pub trait Flusher: core::fmt::Debug + Send { /// Implementor must handle passed log `&str` in some hopefully useful way. fn flush(&self, logs: &str); } /// A way to format logs, user supplied. pub trait Renderer: Send + Sync { /// Implementor must render record into `buf`, returning the slice containing the rendered /// record. fn render<'a>(&self, buf: &'a mut [u8], record: &log::Record) -> &'a [u8]; } static mut LOGGER: Option<&'static dyn logger::TryLogWithStatistics> = None; /// Returns a reference to the logger (as `TryLogWithStatistics` implementation) pub fn logger() -> &'static mut Option<&'static dyn logger::TryLogWithStatistics> { unsafe { &mut LOGGER } } // WARNING: this is not part of the crate's public API and is subject to change at any time. // Taken from `log` crate, mutatis mutandis. // The methods are here and not in `macro` to avoid making the latter public. #[doc(hidden)] pub fn __private_api_try_log( args: fmt::Arguments, level: log::Level, &(target, module_path, file, line): &(&str, &'static str, &'static str, u32), ) -> core::result::Result<(), ()> { crate::logger().ok_or(())?.try_log( &log::Record::builder() .args(args) .level(level) .target(target) .module_path_static(Some(module_path)) .file_static(Some(file)) .line(Some(line)) .build(), ) } // WARNING: this is not part of the crate's public API and is subject to change at any time. #[doc(hidden)] pub fn __private_api_try_log_lit( message: &str, level: log::Level, &(target, module_path, file, line): &(&str, &'static str, &'static str, u32), ) -> core::result::Result<(), ()> { crate::logger().ok_or(())?.try_log( &log::Record::builder() .args(format_args!("{}", message)) .level(level) .target(target) .module_path_static(Some(module_path)) .file_static(Some(file)) .line(Some(line)) .build(), ) } delog-0.1.7/src/logger.rs000064400000000000000000000557301046102023000133510ustar 00000000000000use core::sync::atomic::{AtomicUsize, Ordering}; use core::{cmp, ptr}; /// Semi-abstract characterization of the deferred loggers that the `delog!` macro produces. /// /// # Safety /// This trait is markes "unsafe" to signal that users should never (need to) "write their own", /// but always go through the `delog!` macro. /// /// The user has access to the global logger via `delog::logger()`, but only as TryLog/Log /// implementation, not with this direct access to implementation details. pub unsafe trait Delogger: log::Log + crate::TryLog + State<&'static AtomicUsize> { /// the underlying buffer fn buffer(&self) -> &'static mut [u8]; /// How many characters were claimed so far. fn claimed(&self) -> &'static AtomicUsize; /// Call the flusher. fn flush(&self, logs: &str); /// Actually render the arguments (via internal static buffer). fn render(&self, record: &log::Record) -> &'static [u8]; /// Capacity of circular buffer. fn capacity(&self) -> usize { self.buffer().len() } } /// Trait for either state or statistics of loggers. pub trait State { /// How often was one of the logging macros called. fn attempts(&self) -> T; /// How often was one of the logging macros called without early exit (e.g., buffer not full) fn successes(&self) -> T; /// How often was the flusher called. fn flushes(&self) -> T; /// How many bytes were flushed so far. fn read(&self) -> T; /// How many bytes were logged so far. fn written(&self) -> T; } #[derive(Clone, Copy, Debug)] /// Statistics on logger usage. pub struct Statistics { /// How often was one of the logging macros called. pub attempts: usize, /// How often was one of the logging macros called without early exit (e.g., buffer not full) pub successes: usize, /// How often was the flusher called. pub flushes: usize, /// How many bytes were flushed so far. pub read: usize, /// How many bytes were logged so far. pub written: usize, } /// Fallible, panic-free version of the `log::Log` trait. /// /// The intention is actually that implementors of this trait also /// implement `log::Log` in a panic-free fashion, and simply drop logs /// that can't be logged. Because, if the user can handle the error, they /// would be using the fallible macros, and if not, they most likely do **not** /// want to crash. pub trait TryLog: log::Log { /// Fallible logging call (fails when buffer is full) fn try_log(&self, _: &log::Record) -> core::result::Result<(), ()>; } /// TryLog with some usage statistics on top. pub trait TryLogWithStatistics: TryLog + State { /// Read out statistics on logger usage. fn statistics(&self) -> Statistics { Statistics { attempts: self.attempts(), successes: self.successes(), flushes: self.flushes(), read: self.read(), written: self.written(), } } // /// How often was one of the logging macros called. // fn attempts(&self) -> usize; // /// How often was one of the logging macros called without early exit (e.g., buffer not full) // fn successes(&self) -> usize; // /// How often was the flusher called. // fn flushes(&self) -> usize; // /// How many bytes were flushed so far. // fn read(&self) -> usize; // /// How many bytes were logged so far. // fn written(&self) -> usize; } /// Generate a deferred logger with specified capacity and flushing mechanism. /// /// Note that only the final "runner" generates, initializes and flushes such a deferred logger. /// /// Libraries simply make calls to `log::log!`, or its drop-in replacement `delog::log!`, /// and/or its extension `delog::log_now!`, and/or its alternatives `delog::try_log!` and `delog::try_log_now`, /// and/or the local logging variants `local_log!`. #[cfg(not(any( feature = "max_level_off", all(not(debug_assertions), feature = "release_max_level_off") )))] #[macro_export] macro_rules! delog { ($logger:ident, $capacity:expr, $render_capacity:expr, $flusher:ty) => { delog!( $logger, $capacity, $render_capacity, $flusher, renderer: $crate::render::DefaultRenderer ); impl $logger { #[inline] pub fn init_default( level: $crate::log::LevelFilter, flusher: &'static $flusher, ) -> Result<(), ()> { $logger::init(level, flusher, $crate::render::default()) } } }; ($logger:ident, $capacity:expr, $flusher:ty) => { delog!( $logger, $capacity, $capacity, $flusher, renderer: $crate::render::DefaultRenderer ); impl $logger { #[inline] pub fn init_default( level: $crate::log::LevelFilter, flusher: &'static $flusher, ) -> Result<(), ()> { $logger::init(level, flusher, $crate::render::default()) } } }; ($logger:ident, $capacity:expr, $flusher:ty, renderer: $renderer:ty) => { $crate::delog!($logger, $capacity, $capacity, $flusher, renderer: $renderer); }; ($logger:ident, $capacity:expr, $render_capacity:expr, $flusher:ty, renderer: $renderer:ty) => { #[derive(Clone, Copy)] /// Generated deferred logging implementation. pub struct $logger { flusher: &'static $flusher, renderer: &'static $renderer, // immediate_flusher: &'static $flusher, } // log::Log implementations are required to be Send + Sync unsafe impl Send for $logger {} unsafe impl Sync for $logger {} impl $crate::log::Log for $logger { /// log level is set via log::set_max_level, not here, hence always true fn enabled(&self, _: &$crate::log::Metadata) -> bool { true } /// reads out logs from circular buffer, and flushes via injected flusher fn flush(&self) { let mut buf = [0u8; $capacity]; let logs: &str = unsafe { $crate::dequeue(*self, &mut buf) }; if logs.len() > 0 { use $crate::Flusher; self.flusher.flush(logs); } } fn log(&self, record: &$crate::log::Record) { // use $crate::Delogger; unsafe { $crate::enqueue(*self, record) } } } impl $crate::TryLog for $logger { fn try_log(&self, record: &$crate::log::Record) -> core::result::Result<(), ()> { unsafe { $crate::try_enqueue(*self, record) } } } impl $crate::State for $logger { fn attempts(&self) -> usize { ::attempts(self).load(core::sync::atomic::Ordering::SeqCst) } fn successes(&self) -> usize { ::successes(self).load(core::sync::atomic::Ordering::SeqCst) } fn flushes(&self) -> usize { ::flushes(self).load(core::sync::atomic::Ordering::SeqCst) } fn read(&self) -> usize { ::read(self).load(core::sync::atomic::Ordering::SeqCst) } fn written(&self) -> usize { ::written(self).load(core::sync::atomic::Ordering::SeqCst) } } impl $crate::TryLogWithStatistics for $logger {} #[allow(missing_docs)] impl $logger { #[inline] pub fn init( level: $crate::log::LevelFilter, flusher: &'static $flusher, renderer: &'static $renderer, ) -> Result<(), ()> { use core::sync::atomic::{AtomicBool, Ordering}; static INITIALIZED: AtomicBool = AtomicBool::new(false); if INITIALIZED .compare_exchange_weak(false, true, Ordering::AcqRel, Ordering::Acquire) .is_ok() { // let logger = Self { flusher, immediate_flusher: flusher }; let logger = Self { flusher, renderer }; Self::get().replace(logger); $crate::logger().replace(Self::get().as_ref().unwrap()); $crate::log::set_logger(Self::get().as_ref().unwrap()) .map(|()| $crate::log::set_max_level(level)) .map_err(|_| ()) } else { Err(()) } } fn get() -> &'static mut Option<$logger> { static mut LOGGER: Option<$logger> = None; unsafe { &mut LOGGER } } pub fn flush() { // gracefully degrade if we're not initialized yet if let Some(logger) = Self::get() { $crate::log::Log::flush(logger) } } } impl $crate::State<&'static core::sync::atomic::AtomicUsize> for $logger { fn attempts(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static LOG_ATTEMPT_COUNT: AtomicUsize = AtomicUsize::new(0); &LOG_ATTEMPT_COUNT } fn successes(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static LOG_SUCCESS_COUNT: AtomicUsize = AtomicUsize::new(0); &LOG_SUCCESS_COUNT } fn flushes(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static LOG_FLUSH_COUNT: AtomicUsize = AtomicUsize::new(0); &LOG_FLUSH_COUNT } fn read(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static READ: AtomicUsize = AtomicUsize::new(0); &READ } fn written(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static WRITTEN: AtomicUsize = AtomicUsize::new(0); &WRITTEN } } unsafe impl $crate::Delogger for $logger { fn buffer(&self) -> &'static mut [u8] { static mut BUFFER: [u8; $capacity] = [0u8; $capacity]; unsafe { &mut BUFFER } } fn flush(&self, logs: &str) { use $crate::Flusher; self.flusher.flush(logs) } fn claimed(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static CLAIMED: AtomicUsize = AtomicUsize::new(0); &CLAIMED } fn render(&self, record: &$crate::Record) -> &'static [u8] { static mut LOCAL_BUFFER: [u8; $render_capacity] = [0u8; $render_capacity]; let local_buffer = unsafe { &mut LOCAL_BUFFER }; use $crate::Renderer; self.renderer.render(local_buffer, record) } } }; } /// Generate a deferred logger that will completely optimize out. /// /// Note that the cfg-gate needs to be around the entire macro, as the library /// calling it will not be the crate that has the `max_level_off` feature. #[cfg(any( feature = "max_level_off", all(not(debug_assertions), feature = "release_max_level_off") ))] #[macro_export] macro_rules! delog { ($logger:ident, $capacity:expr, $flusher:ty) => { delog!( $logger, $capacity, $flusher, renderer: $crate::render::DefaultRenderer ); impl $logger { #[inline] pub fn init_default( level: $crate::log::LevelFilter, flusher: &'static $flusher, ) -> Result<(), ()> { Ok(()) } } }; ($logger:ident, $capacity:expr, $flusher:ty, renderer: $renderer:ty) => { #[derive(Clone, Copy)] /// Generated deferred logging implementation. pub struct $logger {} // log::Log implementations are required to be Send + Sync unsafe impl Send for $logger {} unsafe impl Sync for $logger {} impl $crate::log::Log for $logger { /// log level is set via log::set_max_level, not here, hence always true fn enabled(&self, _: &$crate::log::Metadata) -> bool { true } /// reads out logs from circular buffer, and flushes via injected flusher fn flush(&self) {} fn log(&self, _record: &$crate::log::Record) {} } impl $crate::TryLog for $logger { fn try_log(&self, record: &$crate::log::Record) -> core::result::Result<(), ()> { Ok(()) } } impl $crate::State for $logger { fn attempts(&self) -> usize { 0 } fn successes(&self) -> usize { 0 } fn flushes(&self) -> usize { 0 } fn read(&self) -> usize { 0 } fn written(&self) -> usize { 0 } } impl $crate::TryLogWithStatistics for $logger {} #[allow(missing_docs)] impl $logger { #[inline] pub fn init( level: $crate::log::LevelFilter, flusher: &'static $flusher, renderer: &'static $renderer, ) -> Result<(), ()> { Ok(()) } fn get() -> &'static mut Option<$logger> { static mut LOGGER: Option<$logger> = None; unsafe { &mut LOGGER } } pub fn flush() {} } impl $crate::State<&'static core::sync::atomic::AtomicUsize> for $logger { fn attempts(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static LOG_ATTEMPT_COUNT: AtomicUsize = AtomicUsize::new(0); &LOG_ATTEMPT_COUNT } fn successes(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static LOG_SUCCESS_COUNT: AtomicUsize = AtomicUsize::new(0); &LOG_SUCCESS_COUNT } fn flushes(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static LOG_FLUSH_COUNT: AtomicUsize = AtomicUsize::new(0); &LOG_FLUSH_COUNT } fn read(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static READ: AtomicUsize = AtomicUsize::new(0); &READ } fn written(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static WRITTEN: AtomicUsize = AtomicUsize::new(0); &WRITTEN } } unsafe impl $crate::Delogger for $logger { fn buffer(&self) -> &'static mut [u8] { unsafe { &mut [] } } fn flush(&self, logs: &str) {} fn claimed(&self) -> &'static core::sync::atomic::AtomicUsize { use core::sync::atomic::AtomicUsize; static CLAIMED: AtomicUsize = AtomicUsize::new(0); &CLAIMED } fn render(&self, record: &$crate::Record) -> &'static [u8] { &[] } } }; } /// The core "write to circular buffer" method. Marked unsafe to discourage use! /// /// # Safety /// Unfortunately exposed for all to see, as the `delog!` macro needs access to it to /// implement the logger at call site. Hence marked as unsafe. pub unsafe fn enqueue(delogger: impl Delogger, record: &log::Record) { crate::logger::try_enqueue(delogger, record).ok(); } /// The fallible "write to circular buffer" method. Marked unsafe to discourage use! /// /// # Safety /// Unfortunately exposed for all to see, as the `delog!` macro needs access to it to /// implement the logger at call site. Hence marked as unsafe. /// /// This implementation needs some HEAVY testing. It is unsound on PC, where the OS /// can schedule threads in any manner, but assumed to be sound in ARM Cortex-M NVIC /// situations, where interrupts are "nested", in the sense that one may be interrupted, /// then the interrupter can, ..., then the interrupter hands back control, ..., and finally /// the original caller of this function regains control. /// /// In this situation, we keep track of three counters `(read, written, claimed)`, with /// invariants `read <= written <= claimed`. Each writer pessimistically gauges sufficient /// capacity for its log by checking `claimed + size <= read + capacity`, accounting for the /// wraparound. If so, the writer **atomically advances the claim counter**, and starts copying /// its data in this newly claimed space. At the end, it is the duty of the "first" caller /// to advance the `written` counter to the correct state. #[allow(unused_unsafe, unused_variables)] pub unsafe fn try_enqueue( delogger: impl Delogger, record: &log::Record, ) -> core::result::Result<(), ()> { #[cfg(any( feature = "max_level_off", all(not(debug_assertions), feature = "release_max_level_off") ))] { return Ok(()); } #[cfg(not(any( feature = "max_level_off", all(not(debug_assertions), feature = "release_max_level_off") )))] { if record.level() > crate::log::max_level() { return Ok(()); } // keep track of how man logs were attempted delogger.attempts().fetch_add(1, Ordering::SeqCst); if record.target() == "!" { // todo: possibly use separate immediate_flusher let input = delogger.render(record); let input = unsafe { core::str::from_utf8_unchecked(input) }; Delogger::flush(&delogger, input); delogger.successes().fetch_add(1, Ordering::SeqCst); return Ok(()); } let capacity = delogger.capacity(); let log = delogger.render(record); let size = log.len(); let previously_claimed = loop { let read = delogger.read().load(Ordering::SeqCst); let claimed = delogger.claimed().load(Ordering::SeqCst); // figure out the corner cases for "wrap-around" at usize capacity if claimed + size > read + capacity { // not enough space, currently return Err(()); } // try to stake out our claim let previous = delogger.claimed().compare_exchange( claimed, claimed + size, Ordering::SeqCst, Ordering::SeqCst, ); // we were not interrupted, the region is now ours if previous == Ok(claimed) { break claimed; } }; // find out if we're the "first" and will need to update `written` at the end: let written = delogger.written().load(Ordering::SeqCst); let first: bool = written == previously_claimed; // now copy our data - we can be interrupted here at anytime let destination = previously_claimed % capacity; let buffer = delogger.buffer(); if destination + size < capacity { // can do a single copy unsafe { ptr::copy_nonoverlapping(log.as_ptr(), buffer.as_mut_ptr().add(destination), size) }; } else { // need to split let split = capacity - destination; unsafe { ptr::copy_nonoverlapping(log.as_ptr(), buffer.as_mut_ptr().add(destination), split); ptr::copy_nonoverlapping( log.as_ptr().add(split), buffer.as_mut_ptr(), size - split, ); } } if first { // update `written` to current `claimed` (which may be beyond our own claim) loop { let claimed = delogger.claimed().load(Ordering::SeqCst); delogger.written().store(claimed, Ordering::SeqCst); if claimed == delogger.claimed().load(Ordering::SeqCst) { break; } } } delogger.successes().fetch_add(1, Ordering::SeqCst); Ok(()) } } /// The core "read from circular buffer" method. Marked unsafe to discourage use! /// /// # Safety /// Unfortunately exposed for all to see, as the `delog!` macro needs access to it to /// implement the logger at call site. Hence marked as unsafe. #[allow(unused_unsafe)] pub unsafe fn dequeue(delogger: impl Delogger, buf: &mut [u8]) -> &str { delogger.flushes().fetch_add(1, Ordering::SeqCst); // we control the inputs, so we know this is a valid string unsafe { core::str::from_utf8_unchecked(drain_as_bytes(delogger, buf)) } } /// Copy out the contents of the `Logger` ring buffer into the given buffer, /// updating `read` to make space for new log data fn drain_as_bytes(delogger: impl Delogger, buf: &mut [u8]) -> &[u8] { unsafe { let read = delogger.read().load(Ordering::SeqCst); let written = delogger.written().load(Ordering::SeqCst); let p = delogger.buffer().as_ptr(); // early exit to hint the compiler that `n` is not `0` let capacity = delogger.buffer().len(); if capacity == 0 { return &[]; } if written > read { // number of bytes to copy let available = cmp::min(buf.len(), written.wrapping_sub(read)); let r = read % capacity; // NOTE `ptr::copy_nonoverlapping` instead of `copy_from_slice` to avoid panics if r + available > capacity { // two memcpy-s let mid = capacity - r; // buf[..mid].copy_from_slice(&buffer[r..]); ptr::copy_nonoverlapping(p.add(r), buf.as_mut_ptr(), mid); // buf[mid..mid + c].copy_from_slice(&buffer[..available - mid]); ptr::copy_nonoverlapping(p, buf.as_mut_ptr().add(mid), available - mid); } else { // single memcpy // buf[..c].copy_from_slice(&buffer[r..r + c]); ptr::copy_nonoverlapping(p.add(r), buf.as_mut_ptr(), available); } delogger .read() .store(read.wrapping_add(available), Ordering::SeqCst); // &buf[..c] buf.get_unchecked(..available) } else { &[] } } } delog-0.1.7/src/macros.rs000064400000000000000000000277101046102023000133530ustar 00000000000000/// Fallible (ungated) version of `log!`. #[macro_export] #[doc(hidden)] #[cfg(not(feature = "std-log"))] macro_rules! try_log { (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({ let lvl = $lvl; if lvl <= $crate::log::STATIC_MAX_LEVEL && lvl <= $crate::log::max_level() { $crate::__private_api_try_log( ::core::format_args!($($arg)+), lvl, &($target, ::core::module_path!(), ::core::file!(), ::core::line!()), ) } else { Ok(()) } }); ($lvl:expr, $($arg:tt)+) => ($crate::try_log!(target: ::core::module_path!(), $lvl, $($arg)+)) } #[macro_export] #[doc(hidden)] #[cfg(feature = "std-log")] macro_rules! try_log { (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({ $crate::log::log!(target: $target, $lvl, $($arg)+); ::core::result::Result::<(), ()>::Ok(()) }); ($lvl:expr, $($arg:tt)+) => ({ $crate::log::log!($lvl, $($arg)+); ::core::result::Result::<(), ()>::Ok(()) }); } // There is a syntax issue with "repetitions in binding patterns for nested macros", // with a workaround: https://github.com/rust-lang/rust/issues/35853#issuecomment-443110660 // // This is why we want to have `($)` expressions in the following, can just imagine they're not there. // // Unfortunately, I couldn't get this to work, so instead we use the weird `with_dollar_sign!` instead. #[macro_export] #[doc(hidden)] macro_rules! with_dollar_sign { ($($body:tt)*) => { macro_rules! __with_dollar_sign { $($body)* } __with_dollar_sign!($); } } /// Generate logging macros that can be gated by library. /// /// Realize that these macros are generated **in the namespace of the consuming library**, the one /// that actally later makes calls to `local_warn!` etc. /// /// To see this in action, compile documentation using `cargo doc --features example`, or inspect /// the `gate-tests/` subdirectory. #[macro_export] macro_rules! generate_macros { () => { $crate::with_dollar_sign! { ($d:tt) => { /// Fallible version of `debug!`. #[cfg(all(any(feature = "log-all", feature = "log-debug"), not(feature = "log-none")))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_debug { (target: $target:expr, $d($arg:tt)+) => ( $crate::try_log!(target: $target, $crate::Level::Debug, $d($arg)+) ); ($d($arg:tt)+) => ( $crate::try_log!($crate::Level::Debug, $d($arg)+) ); } /// Fallible version of `debug!`. #[cfg(not(all(any(feature = "log-all", feature = "log-debug"), not(feature = "log-none"))))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_debug { // (target: $target:expr, $d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); ($d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); } /// Fallible version of `error!`. #[cfg(all(any(feature = "log-all", feature = "log-error"), not(feature = "log-none")))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_error { (target: $target:expr, $d($arg:tt)+) => ( $crate::try_log!(target: $target, $crate::Level::Error, $d($arg)+) ); ($d($arg:tt)+) => ( $crate::try_log!($crate::Level::Error, $d($arg)+) ); } /// Fallible version of `error!`. #[cfg(not(all(any(feature = "log-all", feature = "log-error"), not(feature = "log-none"))))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_error { // (target: $target:expr, $d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); ($d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); } /// Fallible version of `info!`. #[cfg(all(any(feature = "log-all", feature = "log-info"), not(feature = "log-none")))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_info { (target: $target:expr, $d($arg:tt)+) => ( $crate::try_log!(target: $target, $crate::Level::Info, $d($arg)+) ); ($d($arg:tt)+) => ( $crate::try_log!($crate::Level::Info, $d($arg)+) ); } /// Fallible version of `info!`. #[cfg(not(all(any(feature = "log-all", feature = "log-info"), not(feature = "log-none"))))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_info { // (target: $target:expr, $d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); ($d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); } /// Fallible version of `trace!`. #[cfg(all(any(feature = "log-all", feature = "log-trace"), not(feature = "log-none")))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_trace { (target: $target:expr, $d($arg:tt)+) => ( $crate::try_log!(target: $target, $crate::Level::Trace, $d($arg)+) ); ($d($arg:tt)+) => ( $crate::try_log!($crate::Level::Trace, $d($arg)+) ); } /// Fallible version of `trace!`. #[cfg(not(all(any(feature = "log-all", feature = "log-trace"), not(feature = "log-none"))))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_trace { (target: $target:expr, $d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); ($d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); } /// Fallible version of `warn!`. #[cfg(all(any(feature = "log-all", feature = "log-warn"), not(feature = "log-none")))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_warn { (target: $target:expr, $d($arg:tt)+) => ( $crate::try_log!(target: $target, $crate::Level::Warn, $d($arg)+) ); ($d($arg:tt)+) => ( $crate::try_log!($crate::Level::Warn, $d($arg)+) ); } /// Fallible version of `warn!`. #[cfg(not(all(any(feature = "log-all", feature = "log-warn"), not(feature = "log-none"))))] #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! try_warn { (target: $target:expr, $d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); ($d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); } #[cfg(not(feature = "log-none"))] /// Local version of `log!`. #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! log { (target: $target:expr, $d($arg:tt)+) => ( $crate::try_log!(target: $target, $d($arg)+).ok() ); ($d($arg:tt)+) => ( $crate::try_log!($d($arg)+).ok() ); } #[cfg(feature = "log-none")] /// Local version of `log!`. #[macro_use] #[macro_export] #[doc(hidden)] macro_rules! log { ($d($arg:tt)+) => ( core::result::Result::<(), ()>::Ok(()) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Local version of `debug!`. macro_rules! debug { ($d($arg:tt)+) => ( try_debug!($d($arg)+).ok() ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Local version of `error!`. macro_rules! error { ($d($arg:tt)+) => ( try_error!($d($arg)+).ok() ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Local version of `info!`. macro_rules! info { ($d($arg:tt)+) => ( try_info!($d($arg)+).ok() ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Local version of `trace!`. macro_rules! trace { ($d($arg:tt)+) => ( try_trace!($d($arg)+).ok() ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Local version of `warn!`. macro_rules! warn { ($d($arg:tt)+) => ( try_warn!($d($arg)+).ok() ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Immediate version of `log!`. macro_rules! log_now { ($lvl:expr, $d($arg:tt)+) => ( log!(target: "!", $lvl, $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Immediate version of `debug!`. macro_rules! debug_now { ($d($arg:tt)+) => ( debug!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Immediate version of `error!`. macro_rules! error_now { ($d($arg:tt)+) => ( error!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Immediate version of `info!`. macro_rules! info_now { ($d($arg:tt)+) => ( info!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Immediate version of `trace!`. macro_rules! trace_now { ($d($arg:tt)+) => ( trace!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Immediate version of `warn!`. macro_rules! warn_now { ($d($arg:tt)+) => ( warn!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Fallible immediate version of `log!`. macro_rules! try_log_now { ($lvl:expr, $d($arg:tt)+) => ( try_log!(target: "!", $lvl, $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Fallible immediate version of `debug!`. macro_rules! try_debug_now { ($d($arg:tt)+) => ( try_debug!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Fallible immediate version of `error!`. macro_rules! try_error_now { ($d($arg:tt)+) => ( try_error!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Fallible immediate version of `info!`. macro_rules! try_info_now { ($d($arg:tt)+) => ( try_info!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Fallible immediate version of `trace!`. macro_rules! try_trace_now { ($d($arg:tt)+) => ( try_trace!(target: "!", $d($arg)+) ); } #[macro_use] #[macro_export] #[doc(hidden)] /// Fallible immediate version of `warn!`. macro_rules! try_warn_now { ($d($arg:tt)+) => ( try_warn!(target: "!", $d($arg)+) ); } } } } } delog-0.1.7/src/render.rs000064400000000000000000000076371046102023000133540ustar 00000000000000//! The default, minimal renderer, and some helper functions. use core::{cmp, fmt}; /// For some reason, there seems to be no existing method to easily render /// fmt::Arguments in a pre-allocated byte array. /// /// That is what this does. pub fn render_arguments<'a>(buf: &'a mut [u8], args: fmt::Arguments) -> &'a [u8] { let mut writer = WriteTo::new(buf); core::fmt::write(&mut writer, args).ok(); writer.endl(); let used = writer.used; &buf[..used] } /// Render record, based on feature flags. pub fn render_record<'a>(buf: &'a mut [u8], record: &log::Record) -> &'a [u8] { if cfg!(feature = "prefix-level") { match (record.file(), record.line()) { (Some(file), Some(line)) => render_arguments( buf, format_args!( "{}|{}|{}:{}: {}", record.level(), record.target(), file, line, record.args() ), ), _ => render_arguments( buf, format_args!("{}|{}: {}", record.level(), record.target(), record.args()), ), } } else { render_arguments(buf, *record.args()) } } // I don't get it, why isn't this implemented already? struct WriteTo<'a> { buffer: &'a mut [u8], // on write error (i.e. not enough space in buffer) this grows beyond // `buffer.len()`. used: usize, } impl<'a> WriteTo<'a> { pub fn new(buffer: &'a mut [u8]) -> Self { WriteTo { buffer, used: 0 } } pub fn endl(&mut self) { if self.used < self.buffer.len() { self.buffer[self.used] = b'\n'; self.used += 1; } } } impl<'a> core::fmt::Write for WriteTo<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { if self.used > self.buffer.len() { return Err(fmt::Error); } let remaining_buf = &mut self.buffer[self.used..]; let raw_s = s.as_bytes(); let write_num = cmp::min(raw_s.len(), remaining_buf.len()); remaining_buf[..write_num].copy_from_slice(&raw_s[..write_num]); self.used += write_num; if write_num < raw_s.len() { Err(fmt::Error) } else { Ok(()) } } } use crate::Renderer; #[derive(Clone, Copy)] /// Renders just the `record.args()`. pub struct DefaultRenderer {} /// The default, minimal renderer. pub fn default() -> &'static DefaultRenderer { static RENDERER: DefaultRenderer = DefaultRenderer {}; &RENDERER } impl Renderer for DefaultRenderer { fn render<'a>(&self, buf: &'a mut [u8], record: &log::Record) -> &'a [u8] { render_arguments(buf, *record.args()) } } unsafe impl Send for DefaultRenderer {} unsafe impl Sync for DefaultRenderer {} #[derive(Clone, Copy)] /// Renders the `record.args()`, prefixed by level, target, and file, line if they are some. pub struct RipgrepRenderer {} impl Renderer for RipgrepRenderer { fn render<'a>(&self, buf: &'a mut [u8], record: &log::Record) -> &'a [u8] { match (record.file(), record.line()) { (Some(file), Some(line)) => render_arguments( buf, format_args!( "{}|{}|{}:{}: {}", record.level(), record.target(), file, line, record.args() ), ), (Some(file), None) => render_arguments( buf, format_args!( "{}|{}|{}: {}", record.level(), record.target(), file, record.args() ), ), _ => render_arguments( buf, format_args!("{}|{}: {}", record.level(), record.target(), record.args()), ), } } } delog-0.1.7/src/snapshots/delog__hex__test__custom_hex_str.snap000064400000000000000000000002361046102023000232000ustar 00000000000000--- source: src/hex.rs expression: "format_args!(\"'{:02X}'\", HexStr :: < _, SpaceSeparator, typenum :: U3 >\n (& buf),)" --- '010203 A1B7FF 03' delog-0.1.7/src/snapshots/delog__hex__test__hex_str-2.snap000064400000000000000000000001521046102023000217420ustar 00000000000000--- source: src/hex.rs expression: "format_args!(\"'{:02X}'\", hex_str_2(& buf))" --- '0102 03A1 B7FF 03' delog-0.1.7/src/snapshots/delog__hex__test__hex_str-3.snap000064400000000000000000000001521046102023000217430ustar 00000000000000--- source: src/hex.rs expression: "format_args!(\"'{:02x}'\", hex_str_2(& buf))" --- '0102 03a1 b7ff 03' delog-0.1.7/src/snapshots/delog__hex__test__hex_str-4.snap000064400000000000000000000001501046102023000217420ustar 00000000000000--- source: src/hex.rs expression: "format_args!(\"'{:02X}'\", hex_str_4(& buf))" --- '010203A1 B7FF03' delog-0.1.7/src/snapshots/delog__hex__test__hex_str-5.snap000064400000000000000000000001551046102023000217500ustar 00000000000000--- source: src/hex.rs expression: "format_args!(\"'{:02X}'\", hex_str_4(& buf [..]))" --- '010203A1 B7FF03' delog-0.1.7/src/snapshots/delog__hex__test__hex_str-6.snap000064400000000000000000000001501046102023000217440ustar 00000000000000--- source: src/hex.rs expression: "format_args!(\"'{:02X}'\", hex_str_4(& buf))" --- '010203A1 B7FF03' delog-0.1.7/src/snapshots/delog__hex__test__hex_str-7.snap000064400000000000000000000001461046102023000217520ustar 00000000000000--- source: src/hex.rs expression: "format_args!(\"'{:X}'\", hex_str_4(& buf))" --- '010203A1 B7FF03' delog-0.1.7/src/snapshots/delog__hex__test__hex_str.snap000064400000000000000000000001551046102023000216060ustar 00000000000000--- source: src/hex.rs expression: "format_args!(\"'{:02X}'\", hex_str_1(& buf))" --- '01 02 03 A1 B7 FF 03'