├── .cargo └── config.toml ├── .editorconfig ├── .github ├── semantic.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── fastimer-driver ├── Cargo.toml ├── README.md ├── src │ ├── heap.rs │ └── lib.rs └── tests │ └── integration.rs ├── fastimer-tokio ├── Cargo.toml ├── README.md └── src │ └── lib.rs ├── fastimer ├── Cargo.toml ├── src │ ├── interval.rs │ ├── lib.rs │ ├── schedule │ │ ├── arbitrary.rs │ │ ├── mod.rs │ │ ├── notify.rs │ │ ├── select.rs │ │ └── simple.rs │ └── timeout.rs └── tests │ ├── common │ └── mod.rs │ ├── interval.rs │ └── schedule.rs ├── licenserc.toml ├── rust-toolchain.toml ├── rustfmt.toml ├── taplo.toml ├── typos.toml └── xtask ├── Cargo.toml └── src └── main.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [alias] 16 | x = "run --package x --" 17 | 18 | [env] 19 | CARGO_WORKSPACE_DIR = { value = "", relative = true } 20 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | indent_style = space 6 | insert_final_newline = true 7 | trim_trailing_whitespace = true 8 | 9 | [*.toml] 10 | indent_size = tab 11 | tab_width = 2 12 | -------------------------------------------------------------------------------- /.github/semantic.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # The pull request's title should be fulfilled the following pattern: 16 | # 17 | # [optional scope]: 18 | # 19 | # ... where valid types and scopes can be found below; for example: 20 | # 21 | # build(maven): One level down for native profile 22 | # 23 | # More about configurations on https://github.com/Ezard/semantic-prs#configuration 24 | 25 | enabled: true 26 | 27 | titleOnly: true 28 | 29 | types: 30 | - feat 31 | - fix 32 | - docs 33 | - style 34 | - refactor 35 | - perf 36 | - test 37 | - build 38 | - ci 39 | - chore 40 | - revert 41 | 42 | targetUrl: https://github.com/fast/fastimer/blob/main/.github/semantic.yml 43 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: CI 16 | on: 17 | pull_request: 18 | branches: [ main ] 19 | push: 20 | branches: [ main ] 21 | 22 | # Concurrency strategy: 23 | # github.workflow: distinguish this workflow from others 24 | # github.event_name: distinguish `push` event from `pull_request` event 25 | # github.event.number: set to the number of the pull request if `pull_request` event 26 | # github.run_id: otherwise, it's a `push` event, only cancel if we rerun the workflow 27 | # 28 | # Reference: 29 | # https://docs.github.com/en/actions/using-jobs/using-concurrency 30 | # https://docs.github.com/en/actions/learn-github-actions/contexts#github-context 31 | concurrency: 32 | group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.number || github.run_id }} 33 | cancel-in-progress: true 34 | 35 | jobs: 36 | check: 37 | name: Check 38 | runs-on: ubuntu-22.04 39 | steps: 40 | - uses: actions/checkout@v4 41 | - name: Install toolchain 42 | uses: dtolnay/rust-toolchain@nightly 43 | with: 44 | components: rustfmt,clippy 45 | - uses: Swatinem/rust-cache@v2 46 | - uses: taiki-e/install-action@v2 47 | with: 48 | tool: typos-cli,taplo-cli,hawkeye 49 | - run: cargo +nightly x lint 50 | 51 | test: 52 | name: Run tests 53 | strategy: 54 | matrix: 55 | os: [ ubuntu-22.04, macos-14, windows-2022 ] 56 | rust-version: [ "1.85.0", "stable" ] 57 | runs-on: ${{ matrix.os }} 58 | steps: 59 | - uses: actions/checkout@v4 60 | - uses: Swatinem/rust-cache@v2 61 | - name: Delete rust-toolchain.toml 62 | run: rm rust-toolchain.toml 63 | - name: Install toolchain 64 | uses: dtolnay/rust-toolchain@master 65 | with: 66 | toolchain: ${{ matrix.rust-version }} 67 | - name: Run unit tests 68 | run: cargo x test --no-capture 69 | shell: bash 70 | 71 | required: 72 | name: Required 73 | runs-on: ubuntu-22.04 74 | if: ${{ always() }} 75 | needs: 76 | - check 77 | - test 78 | steps: 79 | - name: Guardian 80 | run: | 81 | if [[ ! ( \ 82 | "${{ needs.check.result }}" == "success" \ 83 | && "${{ needs.test.result }}" == "success" \ 84 | ) ]]; then 85 | echo "Required jobs haven't been completed successfully." 86 | exit -1 87 | fi 88 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "addr2line" 7 | version = "0.24.2" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" 10 | dependencies = [ 11 | "gimli", 12 | ] 13 | 14 | [[package]] 15 | name = "adler2" 16 | version = "2.0.0" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" 19 | 20 | [[package]] 21 | name = "aho-corasick" 22 | version = "1.1.3" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" 25 | dependencies = [ 26 | "memchr", 27 | ] 28 | 29 | [[package]] 30 | name = "anstream" 31 | version = "0.6.18" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" 34 | dependencies = [ 35 | "anstyle", 36 | "anstyle-parse", 37 | "anstyle-query", 38 | "anstyle-wincon", 39 | "colorchoice", 40 | "is_terminal_polyfill", 41 | "utf8parse", 42 | ] 43 | 44 | [[package]] 45 | name = "anstyle" 46 | version = "1.0.10" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" 49 | 50 | [[package]] 51 | name = "anstyle-parse" 52 | version = "0.2.6" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" 55 | dependencies = [ 56 | "utf8parse", 57 | ] 58 | 59 | [[package]] 60 | name = "anstyle-query" 61 | version = "1.1.2" 62 | source = "registry+https://github.com/rust-lang/crates.io-index" 63 | checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" 64 | dependencies = [ 65 | "windows-sys 0.59.0", 66 | ] 67 | 68 | [[package]] 69 | name = "anstyle-wincon" 70 | version = "3.0.6" 71 | source = "registry+https://github.com/rust-lang/crates.io-index" 72 | checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" 73 | dependencies = [ 74 | "anstyle", 75 | "windows-sys 0.59.0", 76 | ] 77 | 78 | [[package]] 79 | name = "anyhow" 80 | version = "1.0.98" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" 83 | 84 | [[package]] 85 | name = "atomic-waker" 86 | version = "1.1.2" 87 | source = "registry+https://github.com/rust-lang/crates.io-index" 88 | checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" 89 | 90 | [[package]] 91 | name = "autocfg" 92 | version = "1.4.0" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" 95 | 96 | [[package]] 97 | name = "backtrace" 98 | version = "0.3.74" 99 | source = "registry+https://github.com/rust-lang/crates.io-index" 100 | checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" 101 | dependencies = [ 102 | "addr2line", 103 | "cfg-if", 104 | "libc", 105 | "miniz_oxide", 106 | "object", 107 | "rustc-demangle", 108 | "windows-targets", 109 | ] 110 | 111 | [[package]] 112 | name = "bitflags" 113 | version = "2.6.0" 114 | source = "registry+https://github.com/rust-lang/crates.io-index" 115 | checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" 116 | 117 | [[package]] 118 | name = "bytes" 119 | version = "1.10.0" 120 | source = "registry+https://github.com/rust-lang/crates.io-index" 121 | checksum = "f61dac84819c6588b558454b194026eb1f09c293b9036ae9b159e74e73ab6cf9" 122 | 123 | [[package]] 124 | name = "cfg-if" 125 | version = "1.0.0" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 128 | 129 | [[package]] 130 | name = "clap" 131 | version = "4.5.23" 132 | source = "registry+https://github.com/rust-lang/crates.io-index" 133 | checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84" 134 | dependencies = [ 135 | "clap_builder", 136 | "clap_derive", 137 | ] 138 | 139 | [[package]] 140 | name = "clap_builder" 141 | version = "4.5.23" 142 | source = "registry+https://github.com/rust-lang/crates.io-index" 143 | checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838" 144 | dependencies = [ 145 | "anstream", 146 | "anstyle", 147 | "clap_lex", 148 | "strsim", 149 | ] 150 | 151 | [[package]] 152 | name = "clap_derive" 153 | version = "4.5.18" 154 | source = "registry+https://github.com/rust-lang/crates.io-index" 155 | checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" 156 | dependencies = [ 157 | "heck", 158 | "proc-macro2", 159 | "quote", 160 | "syn", 161 | ] 162 | 163 | [[package]] 164 | name = "clap_lex" 165 | version = "0.7.4" 166 | source = "registry+https://github.com/rust-lang/crates.io-index" 167 | checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" 168 | 169 | [[package]] 170 | name = "colorchoice" 171 | version = "1.0.3" 172 | source = "registry+https://github.com/rust-lang/crates.io-index" 173 | checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" 174 | 175 | [[package]] 176 | name = "colored" 177 | version = "3.0.0" 178 | source = "registry+https://github.com/rust-lang/crates.io-index" 179 | checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" 180 | dependencies = [ 181 | "windows-sys 0.59.0", 182 | ] 183 | 184 | [[package]] 185 | name = "crossbeam-queue" 186 | version = "0.3.12" 187 | source = "registry+https://github.com/rust-lang/crates.io-index" 188 | checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" 189 | dependencies = [ 190 | "crossbeam-utils", 191 | ] 192 | 193 | [[package]] 194 | name = "crossbeam-utils" 195 | version = "0.8.21" 196 | source = "registry+https://github.com/rust-lang/crates.io-index" 197 | checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" 198 | 199 | [[package]] 200 | name = "either" 201 | version = "1.13.0" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" 204 | 205 | [[package]] 206 | name = "env_filter" 207 | version = "0.1.3" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0" 210 | dependencies = [ 211 | "log", 212 | "regex", 213 | ] 214 | 215 | [[package]] 216 | name = "errno" 217 | version = "0.3.10" 218 | source = "registry+https://github.com/rust-lang/crates.io-index" 219 | checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" 220 | dependencies = [ 221 | "libc", 222 | "windows-sys 0.59.0", 223 | ] 224 | 225 | [[package]] 226 | name = "fastimer" 227 | version = "0.9.0" 228 | dependencies = [ 229 | "log", 230 | "logforth", 231 | "pin-project", 232 | "tokio", 233 | ] 234 | 235 | [[package]] 236 | name = "fastimer-driver" 237 | version = "0.9.0" 238 | dependencies = [ 239 | "atomic-waker", 240 | "crossbeam-queue", 241 | "fastimer", 242 | "parking", 243 | "tokio", 244 | ] 245 | 246 | [[package]] 247 | name = "fastimer-tokio" 248 | version = "0.9.0" 249 | dependencies = [ 250 | "fastimer", 251 | "tokio", 252 | ] 253 | 254 | [[package]] 255 | name = "gimli" 256 | version = "0.31.1" 257 | source = "registry+https://github.com/rust-lang/crates.io-index" 258 | checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" 259 | 260 | [[package]] 261 | name = "heck" 262 | version = "0.5.0" 263 | source = "registry+https://github.com/rust-lang/crates.io-index" 264 | checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" 265 | 266 | [[package]] 267 | name = "home" 268 | version = "0.5.9" 269 | source = "registry+https://github.com/rust-lang/crates.io-index" 270 | checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" 271 | dependencies = [ 272 | "windows-sys 0.52.0", 273 | ] 274 | 275 | [[package]] 276 | name = "is_terminal_polyfill" 277 | version = "1.70.1" 278 | source = "registry+https://github.com/rust-lang/crates.io-index" 279 | checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" 280 | 281 | [[package]] 282 | name = "jiff" 283 | version = "0.2.8" 284 | source = "registry+https://github.com/rust-lang/crates.io-index" 285 | checksum = "e5ad87c89110f55e4cd4dc2893a9790820206729eaf221555f742d540b0724a0" 286 | dependencies = [ 287 | "jiff-static", 288 | "jiff-tzdb-platform", 289 | "log", 290 | "portable-atomic", 291 | "portable-atomic-util", 292 | "serde", 293 | "windows-sys 0.59.0", 294 | ] 295 | 296 | [[package]] 297 | name = "jiff-static" 298 | version = "0.2.8" 299 | source = "registry+https://github.com/rust-lang/crates.io-index" 300 | checksum = "d076d5b64a7e2fe6f0743f02c43ca4a6725c0f904203bfe276a5b3e793103605" 301 | dependencies = [ 302 | "proc-macro2", 303 | "quote", 304 | "syn", 305 | ] 306 | 307 | [[package]] 308 | name = "jiff-tzdb" 309 | version = "0.1.4" 310 | source = "registry+https://github.com/rust-lang/crates.io-index" 311 | checksum = "c1283705eb0a21404d2bfd6eef2a7593d240bc42a0bdb39db0ad6fa2ec026524" 312 | 313 | [[package]] 314 | name = "jiff-tzdb-platform" 315 | version = "0.1.3" 316 | source = "registry+https://github.com/rust-lang/crates.io-index" 317 | checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" 318 | dependencies = [ 319 | "jiff-tzdb", 320 | ] 321 | 322 | [[package]] 323 | name = "libc" 324 | version = "0.2.169" 325 | source = "registry+https://github.com/rust-lang/crates.io-index" 326 | checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" 327 | 328 | [[package]] 329 | name = "linux-raw-sys" 330 | version = "0.4.14" 331 | source = "registry+https://github.com/rust-lang/crates.io-index" 332 | checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" 333 | 334 | [[package]] 335 | name = "lock_api" 336 | version = "0.4.12" 337 | source = "registry+https://github.com/rust-lang/crates.io-index" 338 | checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" 339 | dependencies = [ 340 | "autocfg", 341 | "scopeguard", 342 | ] 343 | 344 | [[package]] 345 | name = "log" 346 | version = "0.4.27" 347 | source = "registry+https://github.com/rust-lang/crates.io-index" 348 | checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" 349 | 350 | [[package]] 351 | name = "logforth" 352 | version = "0.24.0" 353 | source = "registry+https://github.com/rust-lang/crates.io-index" 354 | checksum = "e7d12336d4771854b6fdbf75bab8257e62d4221d1f9d7187fc254b29aa3bd23b" 355 | dependencies = [ 356 | "anyhow", 357 | "colored", 358 | "env_filter", 359 | "jiff", 360 | "log", 361 | ] 362 | 363 | [[package]] 364 | name = "memchr" 365 | version = "2.7.4" 366 | source = "registry+https://github.com/rust-lang/crates.io-index" 367 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 368 | 369 | [[package]] 370 | name = "miniz_oxide" 371 | version = "0.8.3" 372 | source = "registry+https://github.com/rust-lang/crates.io-index" 373 | checksum = "b8402cab7aefae129c6977bb0ff1b8fd9a04eb5b51efc50a70bea51cda0c7924" 374 | dependencies = [ 375 | "adler2", 376 | ] 377 | 378 | [[package]] 379 | name = "mio" 380 | version = "1.0.3" 381 | source = "registry+https://github.com/rust-lang/crates.io-index" 382 | checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" 383 | dependencies = [ 384 | "libc", 385 | "wasi", 386 | "windows-sys 0.52.0", 387 | ] 388 | 389 | [[package]] 390 | name = "object" 391 | version = "0.36.7" 392 | source = "registry+https://github.com/rust-lang/crates.io-index" 393 | checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" 394 | dependencies = [ 395 | "memchr", 396 | ] 397 | 398 | [[package]] 399 | name = "parking" 400 | version = "2.2.1" 401 | source = "registry+https://github.com/rust-lang/crates.io-index" 402 | checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" 403 | 404 | [[package]] 405 | name = "parking_lot" 406 | version = "0.12.3" 407 | source = "registry+https://github.com/rust-lang/crates.io-index" 408 | checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" 409 | dependencies = [ 410 | "lock_api", 411 | "parking_lot_core", 412 | ] 413 | 414 | [[package]] 415 | name = "parking_lot_core" 416 | version = "0.9.10" 417 | source = "registry+https://github.com/rust-lang/crates.io-index" 418 | checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" 419 | dependencies = [ 420 | "cfg-if", 421 | "libc", 422 | "redox_syscall", 423 | "smallvec", 424 | "windows-targets", 425 | ] 426 | 427 | [[package]] 428 | name = "pin-project" 429 | version = "1.1.9" 430 | source = "registry+https://github.com/rust-lang/crates.io-index" 431 | checksum = "dfe2e71e1471fe07709406bf725f710b02927c9c54b2b5b2ec0e8087d97c327d" 432 | dependencies = [ 433 | "pin-project-internal", 434 | ] 435 | 436 | [[package]] 437 | name = "pin-project-internal" 438 | version = "1.1.9" 439 | source = "registry+https://github.com/rust-lang/crates.io-index" 440 | checksum = "f6e859e6e5bd50440ab63c47e3ebabc90f26251f7c73c3d3e837b74a1cc3fa67" 441 | dependencies = [ 442 | "proc-macro2", 443 | "quote", 444 | "syn", 445 | ] 446 | 447 | [[package]] 448 | name = "pin-project-lite" 449 | version = "0.2.16" 450 | source = "registry+https://github.com/rust-lang/crates.io-index" 451 | checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" 452 | 453 | [[package]] 454 | name = "portable-atomic" 455 | version = "1.11.0" 456 | source = "registry+https://github.com/rust-lang/crates.io-index" 457 | checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" 458 | 459 | [[package]] 460 | name = "portable-atomic-util" 461 | version = "0.2.4" 462 | source = "registry+https://github.com/rust-lang/crates.io-index" 463 | checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" 464 | dependencies = [ 465 | "portable-atomic", 466 | ] 467 | 468 | [[package]] 469 | name = "proc-macro2" 470 | version = "1.0.95" 471 | source = "registry+https://github.com/rust-lang/crates.io-index" 472 | checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" 473 | dependencies = [ 474 | "unicode-ident", 475 | ] 476 | 477 | [[package]] 478 | name = "quote" 479 | version = "1.0.40" 480 | source = "registry+https://github.com/rust-lang/crates.io-index" 481 | checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" 482 | dependencies = [ 483 | "proc-macro2", 484 | ] 485 | 486 | [[package]] 487 | name = "redox_syscall" 488 | version = "0.5.8" 489 | source = "registry+https://github.com/rust-lang/crates.io-index" 490 | checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" 491 | dependencies = [ 492 | "bitflags", 493 | ] 494 | 495 | [[package]] 496 | name = "regex" 497 | version = "1.11.1" 498 | source = "registry+https://github.com/rust-lang/crates.io-index" 499 | checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" 500 | dependencies = [ 501 | "aho-corasick", 502 | "memchr", 503 | "regex-automata", 504 | "regex-syntax", 505 | ] 506 | 507 | [[package]] 508 | name = "regex-automata" 509 | version = "0.4.9" 510 | source = "registry+https://github.com/rust-lang/crates.io-index" 511 | checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" 512 | dependencies = [ 513 | "aho-corasick", 514 | "memchr", 515 | "regex-syntax", 516 | ] 517 | 518 | [[package]] 519 | name = "regex-syntax" 520 | version = "0.8.5" 521 | source = "registry+https://github.com/rust-lang/crates.io-index" 522 | checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" 523 | 524 | [[package]] 525 | name = "rustc-demangle" 526 | version = "0.1.24" 527 | source = "registry+https://github.com/rust-lang/crates.io-index" 528 | checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" 529 | 530 | [[package]] 531 | name = "rustix" 532 | version = "0.38.41" 533 | source = "registry+https://github.com/rust-lang/crates.io-index" 534 | checksum = "d7f649912bc1495e167a6edee79151c84b1bad49748cb4f1f1167f459f6224f6" 535 | dependencies = [ 536 | "bitflags", 537 | "errno", 538 | "libc", 539 | "linux-raw-sys", 540 | "windows-sys 0.52.0", 541 | ] 542 | 543 | [[package]] 544 | name = "scopeguard" 545 | version = "1.2.0" 546 | source = "registry+https://github.com/rust-lang/crates.io-index" 547 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" 548 | 549 | [[package]] 550 | name = "serde" 551 | version = "1.0.219" 552 | source = "registry+https://github.com/rust-lang/crates.io-index" 553 | checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" 554 | dependencies = [ 555 | "serde_derive", 556 | ] 557 | 558 | [[package]] 559 | name = "serde_derive" 560 | version = "1.0.219" 561 | source = "registry+https://github.com/rust-lang/crates.io-index" 562 | checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" 563 | dependencies = [ 564 | "proc-macro2", 565 | "quote", 566 | "syn", 567 | ] 568 | 569 | [[package]] 570 | name = "signal-hook-registry" 571 | version = "1.4.2" 572 | source = "registry+https://github.com/rust-lang/crates.io-index" 573 | checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" 574 | dependencies = [ 575 | "libc", 576 | ] 577 | 578 | [[package]] 579 | name = "smallvec" 580 | version = "1.13.2" 581 | source = "registry+https://github.com/rust-lang/crates.io-index" 582 | checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" 583 | 584 | [[package]] 585 | name = "socket2" 586 | version = "0.5.8" 587 | source = "registry+https://github.com/rust-lang/crates.io-index" 588 | checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8" 589 | dependencies = [ 590 | "libc", 591 | "windows-sys 0.52.0", 592 | ] 593 | 594 | [[package]] 595 | name = "strsim" 596 | version = "0.11.1" 597 | source = "registry+https://github.com/rust-lang/crates.io-index" 598 | checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" 599 | 600 | [[package]] 601 | name = "syn" 602 | version = "2.0.100" 603 | source = "registry+https://github.com/rust-lang/crates.io-index" 604 | checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" 605 | dependencies = [ 606 | "proc-macro2", 607 | "quote", 608 | "unicode-ident", 609 | ] 610 | 611 | [[package]] 612 | name = "tokio" 613 | version = "1.43.0" 614 | source = "registry+https://github.com/rust-lang/crates.io-index" 615 | checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e" 616 | dependencies = [ 617 | "backtrace", 618 | "bytes", 619 | "libc", 620 | "mio", 621 | "parking_lot", 622 | "pin-project-lite", 623 | "signal-hook-registry", 624 | "socket2", 625 | "tokio-macros", 626 | "windows-sys 0.52.0", 627 | ] 628 | 629 | [[package]] 630 | name = "tokio-macros" 631 | version = "2.5.0" 632 | source = "registry+https://github.com/rust-lang/crates.io-index" 633 | checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" 634 | dependencies = [ 635 | "proc-macro2", 636 | "quote", 637 | "syn", 638 | ] 639 | 640 | [[package]] 641 | name = "unicode-ident" 642 | version = "1.0.14" 643 | source = "registry+https://github.com/rust-lang/crates.io-index" 644 | checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" 645 | 646 | [[package]] 647 | name = "utf8parse" 648 | version = "0.2.2" 649 | source = "registry+https://github.com/rust-lang/crates.io-index" 650 | checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" 651 | 652 | [[package]] 653 | name = "wasi" 654 | version = "0.11.0+wasi-snapshot-preview1" 655 | source = "registry+https://github.com/rust-lang/crates.io-index" 656 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 657 | 658 | [[package]] 659 | name = "which" 660 | version = "7.0.0" 661 | source = "registry+https://github.com/rust-lang/crates.io-index" 662 | checksum = "c9cad3279ade7346b96e38731a641d7343dd6a53d55083dd54eadfa5a1b38c6b" 663 | dependencies = [ 664 | "either", 665 | "home", 666 | "rustix", 667 | "winsafe", 668 | ] 669 | 670 | [[package]] 671 | name = "windows-sys" 672 | version = "0.52.0" 673 | source = "registry+https://github.com/rust-lang/crates.io-index" 674 | checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" 675 | dependencies = [ 676 | "windows-targets", 677 | ] 678 | 679 | [[package]] 680 | name = "windows-sys" 681 | version = "0.59.0" 682 | source = "registry+https://github.com/rust-lang/crates.io-index" 683 | checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 684 | dependencies = [ 685 | "windows-targets", 686 | ] 687 | 688 | [[package]] 689 | name = "windows-targets" 690 | version = "0.52.6" 691 | source = "registry+https://github.com/rust-lang/crates.io-index" 692 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" 693 | dependencies = [ 694 | "windows_aarch64_gnullvm", 695 | "windows_aarch64_msvc", 696 | "windows_i686_gnu", 697 | "windows_i686_gnullvm", 698 | "windows_i686_msvc", 699 | "windows_x86_64_gnu", 700 | "windows_x86_64_gnullvm", 701 | "windows_x86_64_msvc", 702 | ] 703 | 704 | [[package]] 705 | name = "windows_aarch64_gnullvm" 706 | version = "0.52.6" 707 | source = "registry+https://github.com/rust-lang/crates.io-index" 708 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" 709 | 710 | [[package]] 711 | name = "windows_aarch64_msvc" 712 | version = "0.52.6" 713 | source = "registry+https://github.com/rust-lang/crates.io-index" 714 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" 715 | 716 | [[package]] 717 | name = "windows_i686_gnu" 718 | version = "0.52.6" 719 | source = "registry+https://github.com/rust-lang/crates.io-index" 720 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" 721 | 722 | [[package]] 723 | name = "windows_i686_gnullvm" 724 | version = "0.52.6" 725 | source = "registry+https://github.com/rust-lang/crates.io-index" 726 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" 727 | 728 | [[package]] 729 | name = "windows_i686_msvc" 730 | version = "0.52.6" 731 | source = "registry+https://github.com/rust-lang/crates.io-index" 732 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" 733 | 734 | [[package]] 735 | name = "windows_x86_64_gnu" 736 | version = "0.52.6" 737 | source = "registry+https://github.com/rust-lang/crates.io-index" 738 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" 739 | 740 | [[package]] 741 | name = "windows_x86_64_gnullvm" 742 | version = "0.52.6" 743 | source = "registry+https://github.com/rust-lang/crates.io-index" 744 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" 745 | 746 | [[package]] 747 | name = "windows_x86_64_msvc" 748 | version = "0.52.6" 749 | source = "registry+https://github.com/rust-lang/crates.io-index" 750 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 751 | 752 | [[package]] 753 | name = "winsafe" 754 | version = "0.0.19" 755 | source = "registry+https://github.com/rust-lang/crates.io-index" 756 | checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" 757 | 758 | [[package]] 759 | name = "x" 760 | version = "0.0.0" 761 | dependencies = [ 762 | "clap", 763 | "which", 764 | ] 765 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [workspace] 16 | members = ["fastimer", "fastimer-driver", "fastimer-tokio", "xtask"] 17 | resolver = "2" 18 | 19 | [workspace.package] 20 | edition = "2024" 21 | homepage = "https://github.com/fast/fastimer" 22 | license = "Apache-2.0" 23 | readme = "README.md" 24 | repository = "https://github.com/fast/fastimer" 25 | rust-version = "1.85.0" 26 | version = "0.9.0" 27 | 28 | [workspace.dependencies] 29 | fastimer = { version = "0.9.0", path = "fastimer" } 30 | tokio = { version = "1.43.0" } 31 | 32 | [workspace.lints.rust] 33 | unknown_lints = "deny" 34 | 35 | [workspace.lints.clippy] 36 | dbg_macro = "deny" 37 | 38 | [workspace.metadata.release] 39 | pre-release-commit-message = "chore: release v{{version}}" 40 | shared-version = true 41 | sign-tag = true 42 | tag-name = "v{{version}}" 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fastimer 2 | 3 | [![Crates.io][crates-badge]][crates-url] 4 | [![Documentation][docs-badge]][docs-url] 5 | [![MSRV 1.85][msrv-badge]](https://www.whatrustisit.com) 6 | [![Apache 2.0 licensed][license-badge]][license-url] 7 | [![Build Status][actions-badge]][actions-url] 8 | 9 | [crates-badge]: https://img.shields.io/crates/v/fastimer.svg 10 | [crates-url]: https://crates.io/crates/fastimer 11 | [docs-badge]: https://docs.rs/fastimer/badge.svg 12 | [msrv-badge]: https://img.shields.io/badge/MSRV-1.85-green?logo=rust 13 | [docs-url]: https://docs.rs/fastimer 14 | [license-badge]: https://img.shields.io/crates/l/fastimer 15 | [license-url]: LICENSE 16 | [actions-badge]: https://github.com/fast/fastimer/workflows/CI/badge.svg 17 | [actions-url]:https://github.com/fast/fastimer/actions?query=workflow%3ACI 18 | 19 | ## Overview 20 | 21 | Fastimer implements runtime-agnostic timer traits and utilities. 22 | 23 | ### Scheduled Actions 24 | 25 | Fastimer provides scheduled actions that can be scheduled as a repeating and cancellable action. 26 | 27 | * `SimpleAction`: A simple repeatable action that can be scheduled with a fixed delay, or at a fixed rate. 28 | * `ArbitraryDelayAction`: A repeatable action that can be scheduled with arbitrary delay. 29 | * `NotifyAction`: A repeatable action that can be scheduled by notifications. 30 | 31 | ### Timeout 32 | 33 | * `Timeout` is a future combinator that completes when the inner future completes or when the timeout expires. 34 | 35 | ### Interval 36 | 37 | * `Interval` ticks at a sequence of instants with a certain duration between each instant. 38 | 39 | ## Installation 40 | 41 | Add the dependency to your `Cargo.toml` via: 42 | 43 | ```shell 44 | cargo add fastimer 45 | ``` 46 | 47 | ## Documentation 48 | 49 | Read the online documents at https://docs.rs/fastimer. 50 | 51 | ## Minimum Supported Rust Version (MSRV) 52 | 53 | This crate is built against the latest stable release, and its minimum supported rustc version is 1.85.0. 54 | 55 | The policy is that the minimum Rust version required to use this crate can be increased in minor version updates. For example, if Fastimer 1.0 requires Rust 1.20.0, then Fastimer 1.0.z for all values of z will also require Rust 1.20.0 or newer. However, Fastimer 1.y for y > 0 may require a newer minimum version of Rust. 56 | 57 | ## License 58 | 59 | This project is licensed under [Apache License, Version 2.0](LICENSE). 60 | -------------------------------------------------------------------------------- /fastimer-driver/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "fastimer-driver" 17 | 18 | description = "This crate implements a timer driver that can work with any async runtime scheduler." 19 | readme = "README.md" 20 | 21 | edition.workspace = true 22 | homepage.workspace = true 23 | license.workspace = true 24 | repository.workspace = true 25 | rust-version.workspace = true 26 | version.workspace = true 27 | 28 | [package.metadata.docs.rs] 29 | all-features = true 30 | rustdoc-args = ["--cfg", "docsrs"] 31 | 32 | [dependencies] 33 | atomic-waker = { version = "1.1.2" } 34 | crossbeam-queue = { version = "0.3.12" } 35 | fastimer = { workspace = true } 36 | parking = { version = "2.2.1" } 37 | 38 | [dev-dependencies] 39 | tokio = { workspace = true, features = ["full"] } 40 | 41 | [lints] 42 | workspace = true 43 | -------------------------------------------------------------------------------- /fastimer-driver/README.md: -------------------------------------------------------------------------------- 1 | # Fastimer Driver 2 | 3 | [![Crates.io][crates-badge]][crates-url] 4 | [![Documentation][docs-badge]][docs-url] 5 | [![MSRV 1.85][msrv-badge]](https://www.whatrustisit.com) 6 | 7 | [crates-badge]: https://img.shields.io/crates/v/fastimer-driver.svg 8 | [crates-url]: https://crates.io/crates/fastimer-driver 9 | [docs-badge]: https://docs.rs/fastimer-driver/badge.svg 10 | [msrv-badge]: https://img.shields.io/badge/MSRV-1.85-green?logo=rust 11 | [docs-url]: https://docs.rs/fastimer-driver 12 | 13 | ## Overview 14 | 15 | This crate implements a timer driver that can work with any async runtime scheduler. 16 | 17 | ## Documentation 18 | 19 | Read the online documents at https://docs.rs/fastimer-driver. 20 | 21 | ## Minimum Supported Rust Version (MSRV) 22 | 23 | This crate is built against the latest stable release, and its minimum supported rustc version is 1.85.0. 24 | 25 | The policy is that the minimum Rust version required to use this crate can be increased in minor version updates. For example, if Fastimer 1.0 requires Rust 1.20.0, then Fastimer 1.0.z for all values of z will also require Rust 1.20.0 or newer. However, Fastimer 1.y for y > 0 may require a newer minimum version of Rust. 26 | 27 | ## License 28 | 29 | This project is licensed under [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). 30 | -------------------------------------------------------------------------------- /fastimer-driver/src/heap.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::BinaryHeap; 16 | use std::ops::ControlFlow; 17 | use std::sync::Arc; 18 | use std::sync::atomic; 19 | use std::sync::atomic::AtomicBool; 20 | use std::time::Duration; 21 | use std::time::Instant; 22 | 23 | use crossbeam_queue::SegQueue; 24 | use parking::Parker; 25 | use parking::Unparker; 26 | 27 | use crate::TimeContext; 28 | use crate::TimeDriverShutdown; 29 | use crate::TimeEntry; 30 | 31 | /// Returns a new time driver, its time context and the shutdown handle. 32 | pub fn binary_heap_driver() -> (BinaryHeapTimeDriver, TimeContext, TimeDriverShutdown) { 33 | let (parker, unparker) = parking::pair(); 34 | let timers = BinaryHeap::new(); 35 | let inbounds = Arc::new(SegQueue::new()); 36 | let shutdown = Arc::new(AtomicBool::new(false)); 37 | 38 | let driver = BinaryHeapTimeDriver { 39 | parker, 40 | unparker, 41 | timers, 42 | inbounds, 43 | shutdown, 44 | }; 45 | 46 | let context = TimeContext { 47 | unparker: driver.unparker.clone(), 48 | inbounds: driver.inbounds.clone(), 49 | }; 50 | 51 | let shutdown = TimeDriverShutdown { 52 | unparker: driver.unparker.clone(), 53 | shutdown: driver.shutdown.clone(), 54 | }; 55 | 56 | (driver, context, shutdown) 57 | } 58 | 59 | /// A heap-based time driver that drives registered timers. 60 | #[derive(Debug)] 61 | pub struct BinaryHeapTimeDriver { 62 | parker: Parker, 63 | unparker: Unparker, 64 | timers: BinaryHeap, 65 | inbounds: Arc>, 66 | shutdown: Arc, 67 | } 68 | 69 | impl BinaryHeapTimeDriver { 70 | /// Drives the timers and returns `true` if the driver has been shut down. 71 | pub fn turn(&mut self) -> ControlFlow<()> { 72 | if self.shutdown.load(atomic::Ordering::Acquire) { 73 | return ControlFlow::Break(()); 74 | } 75 | 76 | match self.timers.peek() { 77 | None => self.parker.park(), 78 | Some(entry) => { 79 | let delta = entry.when.saturating_duration_since(Instant::now()); 80 | if delta > Duration::ZERO { 81 | self.parker.park_timeout(delta); 82 | } 83 | } 84 | } 85 | 86 | while let Some(entry) = self.inbounds.pop() { 87 | self.timers.push(entry); 88 | } 89 | 90 | while let Some(entry) = self.timers.peek() { 91 | if entry.when <= Instant::now() { 92 | entry.waker.wake(); 93 | let _ = self.timers.pop(); 94 | } else { 95 | break; 96 | } 97 | } 98 | 99 | if self.shutdown.load(atomic::Ordering::Acquire) { 100 | ControlFlow::Break(()) 101 | } else { 102 | ControlFlow::Continue(()) 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /fastimer-driver/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![cfg_attr(docsrs, feature(doc_auto_cfg))] 16 | #![deny(missing_docs)] 17 | 18 | //! Runtime-agnostic time driver for creating delay futures. 19 | 20 | use std::cmp; 21 | use std::future::Future; 22 | use std::pin::Pin; 23 | use std::sync::Arc; 24 | use std::sync::atomic; 25 | use std::sync::atomic::AtomicBool; 26 | use std::task::Context; 27 | use std::task::Poll; 28 | use std::time::Duration; 29 | use std::time::Instant; 30 | 31 | use atomic_waker::AtomicWaker; 32 | use crossbeam_queue::SegQueue; 33 | use fastimer::MakeDelay; 34 | use fastimer::make_instant_from_now; 35 | use parking::Unparker; 36 | 37 | mod heap; 38 | pub use heap::*; 39 | 40 | #[derive(Debug)] 41 | struct TimeEntry { 42 | when: Instant, 43 | waker: Arc, 44 | } 45 | 46 | impl PartialEq for TimeEntry { 47 | fn eq(&self, other: &Self) -> bool { 48 | self.when == other.when 49 | } 50 | } 51 | 52 | impl Eq for TimeEntry {} 53 | 54 | impl PartialOrd for TimeEntry { 55 | fn partial_cmp(&self, other: &Self) -> Option { 56 | Some(self.cmp(other)) 57 | } 58 | } 59 | 60 | impl Ord for TimeEntry { 61 | fn cmp(&self, other: &Self) -> cmp::Ordering { 62 | self.when.cmp(&other.when) 63 | } 64 | } 65 | 66 | /// Future returned by [`delay`] and [`delay_until`]. 67 | /// 68 | /// [`delay`]: TimeContext::delay 69 | /// [`delay_until`]: TimeContext::delay_until 70 | #[must_use = "futures do nothing unless you `.await` or poll them"] 71 | #[derive(Debug)] 72 | pub struct Delay { 73 | when: Instant, 74 | waker: Arc, 75 | } 76 | 77 | impl Future for Delay { 78 | type Output = (); 79 | 80 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 81 | if Instant::now() >= self.when { 82 | self.waker.take(); 83 | Poll::Ready(()) 84 | } else { 85 | self.waker.register(cx.waker()); 86 | Poll::Pending 87 | } 88 | } 89 | } 90 | 91 | impl Drop for Delay { 92 | fn drop(&mut self) { 93 | self.waker.take(); 94 | } 95 | } 96 | 97 | /// A time context for creating [`Delay`]s. 98 | #[derive(Debug, Clone)] 99 | pub struct TimeContext { 100 | unparker: Unparker, 101 | inbounds: Arc>, 102 | } 103 | 104 | impl TimeContext { 105 | /// Returns a future that completes after the specified duration. 106 | pub fn delay(&self, dur: Duration) -> Delay { 107 | self.delay_until(make_instant_from_now(dur)) 108 | } 109 | 110 | /// Returns a future that completes at the specified instant. 111 | pub fn delay_until(&self, when: Instant) -> Delay { 112 | let waker = Arc::new(AtomicWaker::new()); 113 | let delay = Delay { 114 | when, 115 | waker: waker.clone(), 116 | }; 117 | self.inbounds.push(TimeEntry { when, waker }); 118 | self.unparker.unpark(); 119 | delay 120 | } 121 | } 122 | 123 | /// A handle to shut down the time driver. 124 | #[derive(Debug, Clone)] 125 | pub struct TimeDriverShutdown { 126 | unparker: Unparker, 127 | shutdown: Arc, 128 | } 129 | 130 | impl TimeDriverShutdown { 131 | /// Shuts down the time driver. 132 | pub fn shutdown(&self) { 133 | self.shutdown.store(true, atomic::Ordering::Release); 134 | self.unparker.unpark(); 135 | } 136 | } 137 | 138 | /// A delay implementation that uses the given time context. 139 | #[derive(Debug, Clone)] 140 | pub struct MakeFastimerDelay(TimeContext); 141 | 142 | impl MakeFastimerDelay { 143 | /// Create a new [`MakeFastimerDelay`] with the given [`TimeContext`]. 144 | pub fn new(context: TimeContext) -> Self { 145 | MakeFastimerDelay(context) 146 | } 147 | } 148 | 149 | impl MakeDelay for MakeFastimerDelay { 150 | type Delay = Delay; 151 | 152 | fn delay_until(&self, at: Instant) -> Self::Delay { 153 | self.0.delay_until(at) 154 | } 155 | 156 | fn delay(&self, duration: Duration) -> Self::Delay { 157 | self.0.delay(duration) 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /fastimer-driver/tests/integration.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::time::Duration; 16 | use std::time::Instant; 17 | 18 | use fastimer::make_instant_from_now; 19 | use fastimer_driver::binary_heap_driver; 20 | 21 | #[track_caller] 22 | fn assert_duration_eq(actual: Duration, expected: Duration) { 23 | if expected.abs_diff(actual) > Duration::from_millis(250) { 24 | panic!("expected: {expected:?}, actual: {actual:?}"); 25 | } 26 | } 27 | 28 | #[test] 29 | fn test_binary_heap_driver() { 30 | let (mut driver, context, shutdown) = binary_heap_driver(); 31 | let (tx, rx) = std::sync::mpsc::channel(); 32 | std::thread::spawn(move || { 33 | loop { 34 | if driver.turn().is_break() { 35 | tx.send(()).unwrap(); 36 | break; 37 | } 38 | } 39 | }); 40 | 41 | let rt = tokio::runtime::Runtime::new().unwrap(); 42 | rt.block_on(async move { 43 | let now = Instant::now(); 44 | 45 | context.delay(Duration::from_secs(2)).await; 46 | assert_duration_eq(now.elapsed(), Duration::from_secs(2)); 47 | 48 | let now = Instant::now(); 49 | let future = make_instant_from_now(Duration::from_secs(3)); 50 | let f1 = context.delay_until(future); 51 | let f2 = context.delay_until(future); 52 | tokio::join!(f1, f2); 53 | assert_duration_eq(now.elapsed(), Duration::from_secs(3)); 54 | 55 | shutdown.shutdown(); 56 | }); 57 | rx.recv_timeout(Duration::from_secs(1)).unwrap(); 58 | } 59 | -------------------------------------------------------------------------------- /fastimer-tokio/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "fastimer-tokio" 17 | 18 | description = "This crate provides tokio runtime integration for fastimer." 19 | readme = "README.md" 20 | 21 | edition.workspace = true 22 | homepage.workspace = true 23 | license.workspace = true 24 | repository.workspace = true 25 | rust-version.workspace = true 26 | version.workspace = true 27 | 28 | [package.metadata.docs.rs] 29 | all-features = true 30 | rustdoc-args = ["--cfg", "docsrs"] 31 | 32 | [features] 33 | spawn = ["dep:fastimer", "dep:tokio", "tokio/rt"] 34 | time = ["dep:fastimer", "dep:tokio", "tokio/time"] 35 | 36 | [dependencies] 37 | fastimer = { workspace = true, optional = true } 38 | tokio = { workspace = true, optional = true } 39 | 40 | [lints] 41 | workspace = true 42 | -------------------------------------------------------------------------------- /fastimer-tokio/README.md: -------------------------------------------------------------------------------- 1 | # Fastimer Tokio 2 | 3 | [![Crates.io][crates-badge]][crates-url] 4 | [![Documentation][docs-badge]][docs-url] 5 | [![MSRV 1.85][msrv-badge]](https://www.whatrustisit.com) 6 | 7 | [crates-badge]: https://img.shields.io/crates/v/fastimer-tokio.svg 8 | [crates-url]: https://crates.io/crates/fastimer-tokio 9 | [docs-badge]: https://docs.rs/fastimer-tokio/badge.svg 10 | [msrv-badge]: https://img.shields.io/badge/MSRV-1.85-green?logo=rust 11 | [docs-url]: https://docs.rs/fastimer-tokio 12 | 13 | ## Overview 14 | 15 | This crate provides tokio runtime integration for fastimer. 16 | 17 | ## Documentation 18 | 19 | Read the online documents at https://docs.rs/fastimer-tokio. 20 | 21 | ## Minimum Supported Rust Version (MSRV) 22 | 23 | This crate is built against the latest stable release, and its minimum supported rustc version is 1.85.0. 24 | 25 | The policy is that the minimum Rust version required to use this crate can be increased in minor version updates. For example, if Fastimer 1.0 requires Rust 1.20.0, then Fastimer 1.0.z for all values of z will also require Rust 1.20.0 or newer. However, Fastimer 1.y for y > 0 may require a newer minimum version of Rust. 26 | 27 | ## License 28 | 29 | This project is licensed under [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). 30 | -------------------------------------------------------------------------------- /fastimer-tokio/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![cfg_attr(docsrs, feature(doc_auto_cfg))] 16 | #![deny(missing_docs)] 17 | 18 | //! [`tokio`] runtime support for [`fastimer`]'s traits. 19 | 20 | #[cfg(feature = "time")] 21 | pub use delay::*; 22 | 23 | #[cfg(feature = "time")] 24 | mod delay { 25 | use std::time::Duration; 26 | use std::time::Instant; 27 | 28 | use fastimer::MakeDelay; 29 | 30 | /// A delay implementation that uses Tokio's timer. 31 | #[derive(Clone, Copy, Debug, Default)] 32 | pub struct MakeTokioDelay; 33 | 34 | impl MakeDelay for MakeTokioDelay { 35 | type Delay = tokio::time::Sleep; 36 | 37 | fn delay_until(&self, at: Instant) -> Self::Delay { 38 | tokio::time::sleep_until(tokio::time::Instant::from_std(at)) 39 | } 40 | 41 | fn delay(&self, duration: Duration) -> Self::Delay { 42 | tokio::time::sleep(duration) 43 | } 44 | } 45 | } 46 | 47 | #[cfg(feature = "spawn")] 48 | pub use spawn::*; 49 | 50 | #[cfg(feature = "spawn")] 51 | mod spawn { 52 | use std::future::Future; 53 | 54 | use fastimer::Spawn; 55 | 56 | /// A spawn implementation that uses Tokio's runtime. 57 | #[derive(Clone, Debug, Default)] 58 | pub struct TokioSpawn(Option); 59 | 60 | impl TokioSpawn { 61 | /// Create a new [`TokioSpawn`] with the given [`tokio::runtime::Handle`]. 62 | pub fn with_handle(mut self, handle: tokio::runtime::Handle) -> Self { 63 | self.0 = Some(handle); 64 | self 65 | } 66 | 67 | /// Create a new [`TokioSpawn`] with the [`tokio::runtime::Handle`] in current context. 68 | pub fn current() -> Self { 69 | Self::default().with_handle(tokio::runtime::Handle::current()) 70 | } 71 | } 72 | 73 | impl Spawn for TokioSpawn { 74 | fn spawn + Send + 'static>(&self, future: F) { 75 | match &self.0 { 76 | None => tokio::spawn(future), 77 | Some(handle) => handle.spawn(future), 78 | }; 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /fastimer/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "fastimer" 17 | 18 | description = "This crate implements runtime-agnostic timer traits and utilities." 19 | 20 | edition.workspace = true 21 | homepage.workspace = true 22 | license.workspace = true 23 | readme.workspace = true 24 | repository.workspace = true 25 | rust-version.workspace = true 26 | version.workspace = true 27 | 28 | [package.metadata.docs.rs] 29 | all-features = true 30 | rustdoc-args = ["--cfg", "docsrs"] 31 | 32 | [features] 33 | logging = ["dep:log"] 34 | 35 | [dependencies] 36 | pin-project = { version = "1.1.9" } 37 | 38 | # optional dependencies 39 | log = { version = "0.4.22", features = ["kv"], optional = true } 40 | 41 | [dev-dependencies] 42 | log = { version = "0.4.22", features = ["kv"] } 43 | logforth = { version = "0.24.0", features = ["colored"] } 44 | tokio = { workspace = true, features = ["full"] } 45 | 46 | [lints] 47 | workspace = true 48 | -------------------------------------------------------------------------------- /fastimer/src/interval.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // This first version of this file is copied from tokio::time::interval [1], while 16 | // fastimer modifies the code to runtime-agnostic. 17 | // 18 | // [1] https://github.com/tokio-rs/tokio/blob/b8ac94ed/tokio/src/time/interval.rs 19 | 20 | use std::future::Future; 21 | use std::future::poll_fn; 22 | use std::pin::Pin; 23 | use std::task::Context; 24 | use std::task::Poll; 25 | use std::task::ready; 26 | use std::time::Duration; 27 | use std::time::Instant; 28 | 29 | use crate::MakeDelay; 30 | use crate::far_future; 31 | 32 | /// Creates new [`Interval`] that yields with interval of `period`. The first 33 | /// tick completes immediately. The default [`MissedTickBehavior`] is 34 | /// [`Burst`](MissedTickBehavior::Burst), but this can be configured 35 | /// by calling [`set_missed_tick_behavior`](Interval::set_missed_tick_behavior). 36 | /// 37 | /// An interval will tick indefinitely. At any time, the [`Interval`] value can 38 | /// be dropped. This cancels the interval. 39 | /// 40 | /// # Panics 41 | /// 42 | /// This function panics if `period` is zero. 43 | /// 44 | /// # Examples 45 | /// 46 | /// ``` 47 | /// # #[tokio::main] 48 | /// # async fn main() { 49 | /// use std::time::Duration; 50 | /// use std::time::Instant; 51 | /// 52 | /// use fastimer::MakeDelay; 53 | /// use fastimer::interval; 54 | /// 55 | /// struct TokioDelay; 56 | /// impl MakeDelay for TokioDelay { 57 | /// type Delay = tokio::time::Sleep; 58 | /// fn delay_until(&self, until: Instant) -> Self::Delay { 59 | /// tokio::time::sleep_until(tokio::time::Instant::from_std(until)) 60 | /// } 61 | /// } 62 | /// 63 | /// let mut interval = interval(Duration::from_millis(10), TokioDelay); 64 | /// 65 | /// interval.tick().await; // ticks immediately 66 | /// interval.tick().await; // ticks after 10ms 67 | /// interval.tick().await; // ticks after 10ms 68 | /// 69 | /// // approximately 20ms have elapsed. 70 | /// # } 71 | /// ``` 72 | /// 73 | /// A simple example using `interval` to execute a task every two seconds. 74 | /// 75 | /// The difference between `interval` and [`delay`] is that an [`Interval`] 76 | /// measures the time since the last tick, which means that [`.tick().await`] 77 | /// may wait for a shorter time than the duration specified for the interval 78 | /// if some time has passed between calls to [`.tick().await`]. 79 | /// 80 | /// If the tick in the example below was replaced with [`delay`], the task 81 | /// would only be executed once every three seconds, and not every two 82 | /// seconds. 83 | /// 84 | /// ``` 85 | /// use std::time::Duration; 86 | /// use std::time::Instant; 87 | /// 88 | /// use fastimer::MakeDelay; 89 | /// use fastimer::interval; 90 | /// 91 | /// struct TokioDelay; 92 | /// impl MakeDelay for TokioDelay { 93 | /// type Delay = tokio::time::Sleep; 94 | /// fn delay_until(&self, until: Instant) -> Self::Delay { 95 | /// tokio::time::sleep_until(tokio::time::Instant::from_std(until)) 96 | /// } 97 | /// } 98 | /// 99 | /// async fn task_that_takes_a_second() { 100 | /// println!("hello"); 101 | /// TokioDelay.delay(Duration::from_secs(1)).await; 102 | /// } 103 | /// 104 | /// #[tokio::main] 105 | /// async fn main() { 106 | /// let mut interval = fastimer::interval(Duration::from_secs(2), TokioDelay); 107 | /// for _ in 0..5 { 108 | /// interval.tick().await; 109 | /// task_that_takes_a_second().await; 110 | /// } 111 | /// } 112 | /// ``` 113 | /// 114 | /// [`delay`]: MakeDelay::delay 115 | /// [`.tick().await`]: Interval::tick 116 | #[track_caller] 117 | pub fn interval(period: Duration, make_delay: D) -> Interval { 118 | assert!(period > Duration::ZERO, "`period` must be non-zero."); 119 | make_interval(Instant::now(), period, make_delay) 120 | } 121 | 122 | /// Creates new [`Interval`] that yields with interval of `period` with the 123 | /// first tick completing at `start`. The default [`MissedTickBehavior`] is 124 | /// [`Burst`](MissedTickBehavior::Burst), but this can be configured 125 | /// by calling [`set_missed_tick_behavior`](Interval::set_missed_tick_behavior). 126 | /// 127 | /// An interval will tick indefinitely. At any time, the [`Interval`] value can 128 | /// be dropped. This cancels the interval. 129 | /// 130 | /// # Panics 131 | /// 132 | /// This function panics if `period` is zero. 133 | /// 134 | /// # Examples 135 | /// 136 | /// ``` 137 | /// # #[tokio::main] 138 | /// # async fn main() { 139 | /// use std::time::Duration; 140 | /// use std::time::Instant; 141 | /// 142 | /// use fastimer::MakeDelay; 143 | /// use fastimer::interval_at; 144 | /// 145 | /// struct TokioDelay; 146 | /// impl MakeDelay for TokioDelay { 147 | /// type Delay = tokio::time::Sleep; 148 | /// fn delay_until(&self, until: Instant) -> Self::Delay { 149 | /// tokio::time::sleep_until(tokio::time::Instant::from_std(until)) 150 | /// } 151 | /// } 152 | /// 153 | /// let start = Instant::now() + Duration::from_millis(50); 154 | /// let mut interval = interval_at(start, Duration::from_millis(10), TokioDelay); 155 | /// 156 | /// interval.tick().await; // ticks after 50ms 157 | /// interval.tick().await; // ticks after 10ms 158 | /// interval.tick().await; // ticks after 10ms 159 | /// 160 | /// // approximately 70ms have elapsed. 161 | /// # } 162 | /// ``` 163 | #[track_caller] 164 | pub fn interval_at(start: Instant, period: Duration, make_delay: D) -> Interval { 165 | assert!(period > Duration::ZERO, "`period` must be non-zero."); 166 | make_interval(start, period, make_delay) 167 | } 168 | 169 | fn make_interval(start: Instant, period: Duration, make_delay: D) -> Interval { 170 | let deadline = start; 171 | let delay = Box::pin(make_delay.delay_until(start)); 172 | Interval { 173 | deadline, 174 | period, 175 | make_delay, 176 | delay, 177 | missed_tick_behavior: MissedTickBehavior::Burst, 178 | } 179 | } 180 | 181 | /// Interval returned by [`interval`] and [`interval_at`]. 182 | /// 183 | /// This type allows you to wait on a sequence of instants with a certain 184 | /// duration between each instant. Unlike calling [`delay`] in a loop, this lets 185 | /// you count the time spent between the calls to [`delay`] as well. 186 | /// 187 | /// [`delay`]: MakeDelay::delay 188 | #[derive(Debug)] 189 | pub struct Interval { 190 | /// The next instant when this interval was scheduled to tick. 191 | deadline: Instant, 192 | 193 | /// The duration between values yielded by this interval. 194 | period: Duration, 195 | 196 | /// The make delay instance used to create the delay future. 197 | make_delay: D, 198 | 199 | /// The delay future of the next tick. 200 | delay: Pin>, 201 | 202 | /// The strategy Interval should use when a tick is missed. 203 | missed_tick_behavior: MissedTickBehavior, 204 | } 205 | 206 | impl Interval { 207 | /// Sets the [`MissedTickBehavior`] strategy that should be used. 208 | pub fn set_missed_tick_behavior(&mut self, behavior: MissedTickBehavior) { 209 | self.missed_tick_behavior = behavior; 210 | } 211 | 212 | /// Returns the [`MissedTickBehavior`] strategy currently being used. 213 | pub fn missed_tick_behavior(&self) -> MissedTickBehavior { 214 | self.missed_tick_behavior 215 | } 216 | 217 | /// Returns the period of the interval. 218 | pub fn period(&self) -> Duration { 219 | self.period 220 | } 221 | 222 | /// Completes when the next instant in the interval has been reached. 223 | /// 224 | /// # Cancel safety 225 | /// 226 | /// This method is cancellation safe. If `tick` is used as the branch in a `tokio::select!` and 227 | /// another branch completes first, then no tick has been consumed. 228 | pub async fn tick(&mut self) -> Instant { 229 | poll_fn(|cx| self.poll_tick(cx)).await 230 | } 231 | 232 | /// Polls for the next instant in the interval to be reached. 233 | /// 234 | /// This method can return the following values: 235 | /// 236 | /// * `Poll::Pending` if the next instant has not yet been reached. 237 | /// * `Poll::Ready(instant)` if the next instant has been reached. 238 | /// 239 | /// When this method returns `Poll::Pending`, the current task is scheduled 240 | /// to receive a wakeup when the instant has elapsed. Note that on multiple 241 | /// calls to `poll_tick`, only the [`Waker`](std::task::Waker) from the 242 | /// [`Context`] passed to the most recent call is scheduled to receive a 243 | /// wakeup. 244 | pub fn poll_tick(&mut self, cx: &mut Context<'_>) -> Poll { 245 | // Wait for the delay to be done 246 | ready!(Pin::new(&mut self.delay).poll(cx)); 247 | 248 | // Get the time when we were scheduled to tick 249 | let timeout = self.deadline; 250 | 251 | let now = Instant::now(); 252 | 253 | // If a tick was not missed, and thus we are being called before the 254 | // next tick is due, just schedule the next tick normally, one `period` 255 | // after `timeout` 256 | // 257 | // However, if a tick took excessively long, and we are now behind, 258 | // schedule the next tick according to how the user specified with 259 | // `MissedTickBehavior` 260 | let next = if now > timeout + Duration::from_millis(5) { 261 | self.missed_tick_behavior 262 | .next_timeout(timeout, now, self.period) 263 | } else { 264 | timeout.checked_add(self.period).unwrap_or_else(far_future) 265 | }; 266 | 267 | // When we arrive here, the internal delay returned `Poll::Ready`. 268 | // Reassign the delay but do not register it. It should be registered with 269 | // the next call to `poll_tick`. 270 | self.delay = Box::pin(self.make_delay.delay_until(next)); 271 | 272 | // Return the time when we were scheduled to tick 273 | self.deadline = next; 274 | Poll::Ready(timeout) 275 | } 276 | } 277 | 278 | /// Defines the behavior of an [`Interval`] when it misses a tick. 279 | #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] 280 | pub enum MissedTickBehavior { 281 | #[default] 282 | /// Ticks as fast as possible until caught up. 283 | Burst, 284 | /// Ticks at multiples of period from when [`tick`] was called, rather than from start. 285 | /// 286 | /// [`tick`]: Interval::tick 287 | Delay, 288 | /// Skips missed ticks and tick on the next multiple of period from start. 289 | Skip, 290 | } 291 | 292 | impl MissedTickBehavior { 293 | /// If a tick is missed, this method is called to determine when the next tick should happen. 294 | fn next_timeout(&self, timeout: Instant, now: Instant, period: Duration) -> Instant { 295 | match self { 296 | Self::Burst => timeout + period, 297 | Self::Delay => now + period, 298 | Self::Skip => { 299 | now + period 300 | - Duration::from_nanos( 301 | ((now - timeout).as_nanos() % period.as_nanos()) 302 | .try_into() 303 | // This operation is practically guaranteed not to 304 | // fail, as in order for it to fail, `period` would 305 | // have to be longer than `now - timeout`, and both 306 | // would have to be longer than 584 years. 307 | // 308 | // If it did fail, there's not a good way to pass 309 | // the error along to the user, so we just panic. 310 | .expect( 311 | "too much time has elapsed since the interval was supposed to tick", 312 | ), 313 | ) 314 | } 315 | } 316 | } 317 | } 318 | -------------------------------------------------------------------------------- /fastimer/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![cfg_attr(docsrs, feature(doc_auto_cfg))] 16 | #![deny(missing_docs)] 17 | 18 | //! Fastimer implements runtime-agnostic timer traits and utilities. 19 | //! 20 | //! # Scheduled Actions 21 | //! 22 | //! Fastimer provides scheduled actions that can be scheduled as a repeating and cancellable action. 23 | //! 24 | //! * [`SimpleAction`]: A simple repeatable action that can be scheduled with a fixed delay, or at a 25 | //! fixed rate. 26 | //! * [`ArbitraryDelayAction`]: A repeatable action that can be scheduled with arbitrary delay. 27 | //! * [`NotifyAction`]: A repeatable action that can be scheduled by notifications. 28 | //! 29 | //! # Timeout 30 | //! 31 | //! [`Timeout`] is a future combinator that completes when the inner future completes or when the 32 | //! timeout expires. 33 | //! 34 | //! # Interval 35 | //! 36 | //! [`Interval`] ticks at a sequence of instants with a certain duration between each instant. 37 | //! 38 | //! [`SimpleAction`]: schedule::SimpleAction 39 | //! [`ArbitraryDelayAction`]: schedule::ArbitraryDelayAction 40 | //! [`NotifyAction`]: schedule::NotifyAction 41 | 42 | use std::future::Future; 43 | use std::time::Duration; 44 | use std::time::Instant; 45 | 46 | mod interval; 47 | pub use interval::*; 48 | 49 | mod timeout; 50 | pub use timeout::*; 51 | 52 | pub mod schedule; 53 | 54 | /// Create a far future instant. 55 | pub fn far_future() -> Instant { 56 | // Roughly 30 years from now. 57 | // API does not provide a way to obtain max `Instant` 58 | // or convert specific date in the future to instant. 59 | // 1000 years overflows on macOS, 100 years overflows on FreeBSD. 60 | Instant::now() + Duration::from_secs(86400 * 365 * 30) 61 | } 62 | 63 | /// Create an instant from the given instant and a duration. 64 | pub fn make_instant_from(now: Instant, dur: Duration) -> Instant { 65 | now.checked_add(dur).unwrap_or_else(far_future) 66 | } 67 | 68 | /// Create an instant from [`Instant::now`] and a duration. 69 | pub fn make_instant_from_now(dur: Duration) -> Instant { 70 | make_instant_from(Instant::now(), dur) 71 | } 72 | 73 | /// A trait for creating delay futures. 74 | /// 75 | /// See [`MakeDelayExt`] for extension methods. 76 | pub trait MakeDelay { 77 | /// The future returned by the `delay`/`delay_until` method. 78 | type Delay: Future + Send; 79 | 80 | /// Create a future that completes at the specified instant. 81 | fn delay_until(&self, at: Instant) -> Self::Delay; 82 | 83 | /// Create a future that completes after the specified duration. 84 | fn delay(&self, duration: Duration) -> Self::Delay { 85 | self.delay_until(make_instant_from_now(duration)) 86 | } 87 | } 88 | 89 | /// A trait for spawning futures. 90 | pub trait Spawn { 91 | /// Spawn a future and return a cancellable future. 92 | fn spawn + Send + 'static>(&self, future: F); 93 | } 94 | 95 | /// Provides extension methods for [`MakeDelay`] implementors. 96 | pub trait MakeDelayExt: MakeDelay { 97 | /// Requires a `Future` to complete before the specified duration has elapsed. 98 | fn timeout(&self, duration: Duration, fut: F) -> Timeout { 99 | timeout(duration, fut, self) 100 | } 101 | 102 | /// Requires a `Future` to complete before the specified instant in time. 103 | fn timeout_at(&self, deadline: Instant, fut: F) -> Timeout { 104 | timeout_at(deadline, fut, self) 105 | } 106 | 107 | /// Creates new [`Interval`] that yields with interval of `period`. 108 | /// 109 | /// See [`interval`] for more details. 110 | fn interval(self, period: Duration) -> Interval 111 | where 112 | Self: Sized, 113 | { 114 | interval(period, self) 115 | } 116 | 117 | /// Creates new [`Interval`] that yields with interval of `period` and starts at `at`. 118 | /// 119 | /// See [`interval_at`] for more details. 120 | fn interval_at(self, at: Instant, period: Duration) -> Interval 121 | where 122 | Self: Sized, 123 | { 124 | interval_at(at, period, self) 125 | } 126 | } 127 | 128 | impl MakeDelayExt for T {} 129 | 130 | pub(crate) use self::macros::debug; 131 | pub(crate) use self::macros::info; 132 | 133 | #[cfg(any(test, feature = "logging"))] 134 | mod macros { 135 | macro_rules! debug { 136 | (target: $target:expr, $($arg:tt)+) => (log::debug!(target: $target, $($arg)+)); 137 | ($($arg:tt)+) => (log::debug!($($arg)+)); 138 | } 139 | 140 | macro_rules! info { 141 | (target: $target:expr, $($arg:tt)+) => (log::info!(target: $target, $($arg)+)); 142 | ($($arg:tt)+) => (log::info!($($arg)+)); 143 | } 144 | 145 | pub(crate) use debug; 146 | pub(crate) use info; 147 | } 148 | 149 | #[cfg(not(any(test, feature = "logging")))] 150 | #[macro_use] 151 | mod macros { 152 | macro_rules! info { 153 | (target: $target:expr, $($arg:tt)+) => {}; 154 | ($($arg:tt)+) => {}; 155 | } 156 | 157 | macro_rules! debug { 158 | (target: $target:expr, $($arg:tt)+) => {}; 159 | ($($arg:tt)+) => {}; 160 | } 161 | 162 | pub(crate) use debug; 163 | pub(crate) use info; 164 | } 165 | -------------------------------------------------------------------------------- /fastimer/src/schedule/arbitrary.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::future::Future; 16 | use std::ops::ControlFlow; 17 | use std::pin::pin; 18 | use std::time::Duration; 19 | use std::time::Instant; 20 | 21 | use crate::MakeDelay; 22 | use crate::Spawn; 23 | use crate::debug; 24 | use crate::info; 25 | use crate::schedule::execute_or_shutdown; 26 | 27 | /// Repeatable action that can be scheduled with arbitrary delay. 28 | /// 29 | /// See [`ArbitraryDelayActionExt`] for scheduling methods. 30 | pub trait ArbitraryDelayAction: Send + 'static { 31 | /// The name of the trait. 32 | fn name(&self) -> &str; 33 | 34 | /// Run the action. 35 | /// 36 | /// Return an Instant that indicates when to schedule the next run. 37 | fn run(&mut self) -> impl Future + Send; 38 | } 39 | 40 | /// An extension trait for [`ArbitraryDelayAction`] that provides scheduling methods. 41 | pub trait ArbitraryDelayActionExt: ArbitraryDelayAction { 42 | /// Creates and executes a repeatable action that becomes enabled first after the given 43 | /// `initial_delay`, and subsequently based on the result of the action. 44 | fn schedule_with_arbitrary_delay( 45 | mut self, 46 | is_shutdown: Fut, 47 | spawn: &S, 48 | make_delay: D, 49 | initial_delay: Option, 50 | ) where 51 | Self: Sized, 52 | Fut: Future + Send + 'static, 53 | S: Spawn, 54 | D: MakeDelay + Send + 'static, 55 | { 56 | spawn.spawn(async move { 57 | info!( 58 | "start scheduled task {} with initial delay {:?}", 59 | self.name(), 60 | initial_delay 61 | ); 62 | 63 | let mut is_shutdown = pin!(is_shutdown); 64 | 'schedule: { 65 | if let Some(initial_delay) = initial_delay { 66 | if initial_delay > Duration::ZERO 67 | && execute_or_shutdown(make_delay.delay(initial_delay), &mut is_shutdown) 68 | .await 69 | .is_break() 70 | { 71 | break 'schedule; 72 | } 73 | } 74 | 75 | loop { 76 | debug!("executing scheduled task {}", self.name()); 77 | 78 | let next = match execute_or_shutdown(self.run(), &mut is_shutdown).await { 79 | ControlFlow::Continue(next) => next, 80 | ControlFlow::Break(()) => break, 81 | }; 82 | 83 | if execute_or_shutdown(make_delay.delay_until(next), &mut is_shutdown) 84 | .await 85 | .is_break() 86 | { 87 | break; 88 | } 89 | } 90 | } 91 | 92 | info!("scheduled task {} is shutdown", self.name()); 93 | }); 94 | } 95 | } 96 | 97 | impl ArbitraryDelayActionExt for T {} 98 | -------------------------------------------------------------------------------- /fastimer/src/schedule/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! Repeatable and cancellable actions. 16 | 17 | mod arbitrary; 18 | 19 | use std::future::Future; 20 | use std::ops::ControlFlow; 21 | 22 | pub use arbitrary::*; 23 | 24 | mod notify; 25 | pub use notify::*; 26 | 27 | mod simple; 28 | pub use simple::*; 29 | 30 | mod select; 31 | use crate::schedule::select::Either; 32 | use crate::schedule::select::select; 33 | 34 | /// Returns [`ControlFlow::Break`] if the caller should shut down; otherwise, 35 | /// returns [`ControlFlow::Continue`] with the result of the action run. 36 | async fn execute_or_shutdown(f: F, is_shutdown: S) -> ControlFlow<(), O> 37 | where 38 | S: Future, 39 | F: Future, 40 | { 41 | match select(is_shutdown, f).await { 42 | Either::Left(()) => ControlFlow::Break(()), 43 | Either::Right(o) => ControlFlow::Continue(o), 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /fastimer/src/schedule/notify.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::future::Future; 16 | use std::pin::pin; 17 | use std::time::Duration; 18 | 19 | use crate::MakeDelay; 20 | use crate::Spawn; 21 | use crate::debug; 22 | use crate::info; 23 | use crate::schedule::execute_or_shutdown; 24 | 25 | /// Repeatable action that can be scheduled by notifications. 26 | /// 27 | /// See [`NotifyActionExt`] for scheduling methods. 28 | pub trait NotifyAction: Send + 'static { 29 | /// The name of the trait. 30 | fn name(&self) -> &str; 31 | 32 | /// Run the action. 33 | fn run(&mut self) -> impl Future + Send; 34 | 35 | /// Return a future that resolves when the action is notified to run again. 36 | fn notified(&mut self) -> impl Future + Send; 37 | } 38 | 39 | /// An extension trait for [`NotifyAction`] that provides scheduling methods. 40 | pub trait NotifyActionExt: NotifyAction { 41 | /// Creates and executes a repeatable action that becomes enabled first after the given 42 | /// `initial_delay`, and subsequently when it is notified. 43 | fn schedule_by_notify( 44 | mut self, 45 | is_shutdown: Fut, 46 | spawn: &S, 47 | make_delay: D, 48 | initial_delay: Option, 49 | ) where 50 | Self: Sized, 51 | Fut: Future + Send + 'static, 52 | S: Spawn, 53 | D: MakeDelay + Send + 'static, 54 | { 55 | spawn.spawn(async move { 56 | info!( 57 | "start scheduled task {} with initial delay {:?}", 58 | self.name(), 59 | initial_delay 60 | ); 61 | 62 | let mut is_shutdown = pin!(is_shutdown); 63 | 'schedule: { 64 | if let Some(initial_delay) = initial_delay { 65 | if initial_delay > Duration::ZERO 66 | && execute_or_shutdown(make_delay.delay(initial_delay), &mut is_shutdown) 67 | .await 68 | .is_break() 69 | { 70 | break 'schedule; 71 | } 72 | } 73 | 74 | loop { 75 | debug!("executing scheduled task {}", self.name()); 76 | 77 | if execute_or_shutdown(self.run(), &mut is_shutdown) 78 | .await 79 | .is_break() 80 | { 81 | break; 82 | }; 83 | 84 | if execute_or_shutdown(self.notified(), &mut is_shutdown) 85 | .await 86 | .is_break() 87 | { 88 | break; 89 | } 90 | } 91 | } 92 | 93 | info!("scheduled task {} is shutdown", self.name()); 94 | }); 95 | } 96 | } 97 | 98 | impl NotifyActionExt for T {} 99 | -------------------------------------------------------------------------------- /fastimer/src/schedule/select.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::future::Future; 16 | use std::pin::Pin; 17 | use std::task::Context; 18 | use std::task::Poll; 19 | 20 | #[derive(Debug, Clone)] 21 | pub enum Either { 22 | Left(A), 23 | Right(B), 24 | } 25 | 26 | #[must_use = "futures do nothing unless you `.await` or poll them"] 27 | #[derive(Debug)] 28 | #[pin_project::pin_project] 29 | pub struct Select { 30 | #[pin] 31 | a: A, 32 | #[pin] 33 | b: B, 34 | } 35 | 36 | impl Future for Select 37 | where 38 | A: Future, 39 | B: Future, 40 | { 41 | type Output = Either; 42 | 43 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 44 | let this = self.project(); 45 | if let Poll::Ready(a) = this.a.poll(cx) { 46 | return Poll::Ready(Either::Left(a)); 47 | } 48 | if let Poll::Ready(b) = this.b.poll(cx) { 49 | return Poll::Ready(Either::Right(b)); 50 | } 51 | Poll::Pending 52 | } 53 | } 54 | 55 | pub fn select(a: A, b: B) -> Select 56 | where 57 | A: Future, 58 | B: Future, 59 | { 60 | Select { a, b } 61 | } 62 | -------------------------------------------------------------------------------- /fastimer/src/schedule/simple.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::future::Future; 16 | use std::pin::pin; 17 | use std::time::Duration; 18 | use std::time::Instant; 19 | 20 | use crate::MakeDelay; 21 | use crate::Spawn; 22 | use crate::debug; 23 | use crate::far_future; 24 | use crate::info; 25 | use crate::make_instant_from; 26 | use crate::make_instant_from_now; 27 | use crate::schedule::execute_or_shutdown; 28 | 29 | /// Repeatable action. 30 | /// 31 | /// See [`SimpleActionExt`] for scheduling methods. 32 | pub trait SimpleAction: Send + 'static { 33 | /// The name of the trait. 34 | fn name(&self) -> &str; 35 | 36 | /// Run the action. 37 | fn run(&mut self) -> impl Future + Send; 38 | } 39 | 40 | /// An extension trait for [`SimpleAction`] that provides scheduling methods. 41 | pub trait SimpleActionExt: SimpleAction { 42 | /// Creates and executes a periodic action that becomes enabled first after the given 43 | /// `initial_delay`, and subsequently with the given `delay` between the termination of one 44 | /// execution and the commencement of the next. 45 | /// 46 | /// This task will terminate if [`SimpleAction::run`] returns `true`. 47 | fn schedule_with_fixed_delay( 48 | mut self, 49 | is_shutdown: Fut, 50 | spawn: &S, 51 | make_delay: D, 52 | initial_delay: Option, 53 | delay: Duration, 54 | ) where 55 | Self: Sized, 56 | Fut: Future + Send + 'static, 57 | S: Spawn, 58 | D: MakeDelay + Send + 'static, 59 | { 60 | spawn.spawn(async move { 61 | info!( 62 | "start scheduled task {} with fixed delay {:?} and initial delay {:?}", 63 | self.name(), 64 | delay, 65 | initial_delay 66 | ); 67 | 68 | let mut is_shutdown = pin!(is_shutdown); 69 | 'schedule: { 70 | if let Some(initial_delay) = initial_delay { 71 | if initial_delay > Duration::ZERO 72 | && execute_or_shutdown(make_delay.delay(initial_delay), &mut is_shutdown) 73 | .await 74 | .is_break() 75 | { 76 | break 'schedule; 77 | } 78 | } 79 | 80 | loop { 81 | debug!("executing scheduled task {}", self.name()); 82 | if execute_or_shutdown(self.run(), &mut is_shutdown) 83 | .await 84 | .is_break() 85 | { 86 | break; 87 | }; 88 | 89 | if execute_or_shutdown(make_delay.delay(delay), &mut is_shutdown) 90 | .await 91 | .is_break() 92 | { 93 | break; 94 | } 95 | } 96 | } 97 | 98 | info!("scheduled task {} is shutdown", self.name()); 99 | }); 100 | } 101 | 102 | /// Creates and executes a periodic action that becomes enabled first after the given 103 | /// `initial_delay`, and subsequently with the given period; that is executions will commence 104 | /// after `initial_delay` then `initial_delay+period`, then `initial_delay+2*period`, and so 105 | /// on. 106 | /// 107 | /// This task will terminate if [`SimpleAction::run`] returns `true`. 108 | /// 109 | /// If any execution of this task takes longer than its period, then subsequent 110 | /// executions may start late, but will not concurrently execute. 111 | fn schedule_at_fixed_rate( 112 | mut self, 113 | is_shutdown: Fut, 114 | spawn: &S, 115 | make_delay: D, 116 | initial_delay: Option, 117 | period: Duration, 118 | ) where 119 | Self: Sized, 120 | Fut: Future + Send + 'static, 121 | S: Spawn, 122 | D: MakeDelay + Send + 'static, 123 | { 124 | assert!(period > Duration::new(0, 0), "`period` must be non-zero."); 125 | 126 | fn calculate_next_on_miss(next: Instant, period: Duration) -> Instant { 127 | let now = Instant::now(); 128 | 129 | if now.saturating_duration_since(next) <= Duration::from_millis(5) { 130 | // finished in time 131 | make_instant_from(next, period) 132 | } else { 133 | // missed the expected execution time; align the next one 134 | match now.checked_add(period) { 135 | None => far_future(), 136 | Some(instant) => { 137 | let delta = (now - next).as_nanos() % period.as_nanos(); 138 | let delta: u64 = delta 139 | .try_into() 140 | // This operation is practically guaranteed not to 141 | // fail, as in order for it to fail, `period` would 142 | // have to be longer than `now - next`, and both 143 | // would have to be longer than 584 years. 144 | // 145 | // If it did fail, there's not a good way to pass 146 | // the error along to the user, so we just panic. 147 | .unwrap_or_else(|_| panic!("too much time has elapsed: {delta}")); 148 | let delta = Duration::from_nanos(delta); 149 | instant - delta 150 | } 151 | } 152 | } 153 | } 154 | 155 | spawn.spawn(async move { 156 | info!( 157 | "start scheduled task {} at fixed rate {:?} with initial delay {:?}", 158 | self.name(), 159 | period, 160 | initial_delay 161 | ); 162 | 163 | let mut is_shutdown = pin!(is_shutdown); 164 | 'schedule: { 165 | let mut next = Instant::now(); 166 | if let Some(initial_delay) = initial_delay { 167 | if initial_delay > Duration::ZERO { 168 | next = make_instant_from_now(initial_delay); 169 | if execute_or_shutdown(make_delay.delay_until(next), &mut is_shutdown) 170 | .await 171 | .is_break() 172 | { 173 | break 'schedule; 174 | } 175 | } 176 | } 177 | 178 | loop { 179 | debug!("executing scheduled task {}", self.name()); 180 | if execute_or_shutdown(self.run(), &mut is_shutdown) 181 | .await 182 | .is_break() 183 | { 184 | break; 185 | }; 186 | 187 | next = calculate_next_on_miss(next, period); 188 | if execute_or_shutdown(make_delay.delay_until(next), &mut is_shutdown) 189 | .await 190 | .is_break() 191 | { 192 | break; 193 | } 194 | } 195 | } 196 | 197 | info!("scheduled task {} is shutdown", self.name()); 198 | }); 199 | } 200 | } 201 | 202 | impl SimpleActionExt for T {} 203 | -------------------------------------------------------------------------------- /fastimer/src/timeout.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::future::Future; 16 | use std::future::IntoFuture; 17 | use std::task::Context; 18 | use std::task::Poll; 19 | use std::time::Duration; 20 | use std::time::Instant; 21 | 22 | use crate::MakeDelay; 23 | 24 | /// Errors returned by [`Timeout`]. 25 | /// 26 | /// This error is returned when a timeout expires before the function was able 27 | /// to finish. 28 | #[derive(Debug, PartialEq, Eq)] 29 | pub struct Elapsed(()); 30 | 31 | /// A future that completes when the inner future completes or when the timeout expires. 32 | /// 33 | /// Created by [`timeout`] or [`timeout_at`]. 34 | #[must_use = "futures do nothing unless you `.await` or poll them"] 35 | #[derive(Debug)] 36 | #[pin_project::pin_project] 37 | pub struct Timeout { 38 | #[pin] 39 | value: T, 40 | #[pin] 41 | delay: D, 42 | } 43 | 44 | impl Timeout { 45 | /// Gets a reference to the underlying value in this timeout. 46 | pub fn get(&self) -> &T { 47 | &self.value 48 | } 49 | 50 | /// Gets a mutable reference to the underlying value in this timeout. 51 | pub fn get_mut(&mut self) -> &mut T { 52 | &mut self.value 53 | } 54 | 55 | /// Consumes this timeout, returning the underlying value. 56 | pub fn into_inner(self) -> T { 57 | self.value 58 | } 59 | } 60 | 61 | impl Future for Timeout 62 | where 63 | T: Future, 64 | D: Future, 65 | { 66 | type Output = Result; 67 | 68 | fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 69 | let this = self.project(); 70 | 71 | if let Poll::Ready(v) = this.value.poll(cx) { 72 | return Poll::Ready(Ok(v)); 73 | } 74 | 75 | match this.delay.poll(cx) { 76 | Poll::Ready(()) => Poll::Ready(Err(Elapsed(()))), 77 | Poll::Pending => Poll::Pending, 78 | } 79 | } 80 | } 81 | 82 | /// Requires a `Future` to complete before the specified duration has elapsed. 83 | pub fn timeout( 84 | duration: Duration, 85 | future: F, 86 | make_delay: &D, 87 | ) -> Timeout 88 | where 89 | F: IntoFuture, 90 | D: MakeDelay + ?Sized, 91 | { 92 | let delay = make_delay.delay(duration); 93 | Timeout { 94 | value: future.into_future(), 95 | delay, 96 | } 97 | } 98 | 99 | /// Requires a `Future` to complete before the specified instant in time. 100 | pub fn timeout_at( 101 | deadline: Instant, 102 | future: F, 103 | make_delay: &D, 104 | ) -> Timeout 105 | where 106 | F: IntoFuture, 107 | D: MakeDelay + ?Sized, 108 | { 109 | let delay = make_delay.delay_until(deadline); 110 | Timeout { 111 | value: future.into_future(), 112 | delay, 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /fastimer/tests/common/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::time::Duration; 16 | use std::time::Instant; 17 | 18 | use fastimer::MakeDelay; 19 | use fastimer::Spawn; 20 | 21 | #[derive(Clone, Copy, Debug, Default)] 22 | pub struct MakeTokioDelay; 23 | 24 | impl MakeDelay for MakeTokioDelay { 25 | type Delay = tokio::time::Sleep; 26 | 27 | fn delay_until(&self, at: Instant) -> Self::Delay { 28 | tokio::time::sleep_until(tokio::time::Instant::from_std(at)) 29 | } 30 | 31 | fn delay(&self, duration: Duration) -> Self::Delay { 32 | tokio::time::sleep(duration) 33 | } 34 | } 35 | 36 | #[derive(Clone, Copy, Debug, Default)] 37 | pub struct TokioSpawn; 38 | 39 | impl Spawn for TokioSpawn { 40 | fn spawn + Send + 'static>(&self, future: F) { 41 | tokio::spawn(future); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /fastimer/tests/interval.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::time::Duration; 16 | use std::time::Instant; 17 | 18 | use fastimer::Interval; 19 | use fastimer::MakeDelay; 20 | use fastimer::MakeDelayExt; 21 | 22 | mod common; 23 | 24 | #[track_caller] 25 | fn assert_duration_eq(actual: Duration, expected: Duration) { 26 | if expected.abs_diff(actual) > Duration::from_millis(250) { 27 | panic!("expected: {expected:?}, actual: {actual:?}"); 28 | } 29 | } 30 | 31 | async fn assert_tick_about(interval: &mut Interval, expected: Duration) { 32 | let start = Instant::now(); 33 | interval.tick().await; 34 | let elapsed = start.elapsed(); 35 | assert_duration_eq(elapsed, expected); 36 | } 37 | 38 | #[tokio::test] 39 | async fn test_interval_ticks() { 40 | let mut interval = common::MakeTokioDelay.interval(Duration::from_secs(1)); 41 | assert_tick_about(&mut interval, Duration::ZERO).await; 42 | 43 | for _ in 0..5 { 44 | assert_tick_about(&mut interval, Duration::from_secs(1)).await; 45 | } 46 | } 47 | 48 | #[tokio::test] 49 | async fn test_interval_at_ticks() { 50 | let first_tick = Instant::now() + Duration::from_secs(2); 51 | 52 | let mut interval = common::MakeTokioDelay.interval_at(first_tick, Duration::from_secs(1)); 53 | assert_tick_about(&mut interval, Duration::from_secs(2)).await; 54 | 55 | for _ in 0..5 { 56 | assert_tick_about(&mut interval, Duration::from_secs(1)).await; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /fastimer/tests/schedule.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::time::Duration; 16 | use std::time::Instant; 17 | 18 | use fastimer::MakeDelay; 19 | use fastimer::schedule::SimpleAction; 20 | use fastimer::schedule::SimpleActionExt; 21 | use logforth::append; 22 | 23 | use crate::common::MakeTokioDelay; 24 | use crate::common::TokioSpawn; 25 | 26 | mod common; 27 | 28 | struct MySimpleAction { 29 | name: &'static str, 30 | counter: u8, 31 | } 32 | 33 | impl MySimpleAction { 34 | fn new(name: &'static str) -> Self { 35 | Self { name, counter: 0 } 36 | } 37 | } 38 | 39 | impl SimpleAction for MySimpleAction { 40 | fn name(&self) -> &str { 41 | self.name 42 | } 43 | 44 | async fn run(&mut self) { 45 | log::info!("[{}] starting turn {}", self.name, self.counter); 46 | MakeTokioDelay.delay(Duration::from_secs(1)).await; 47 | self.counter += 1; 48 | } 49 | } 50 | 51 | #[tokio::test] 52 | async fn test_simple_action() { 53 | let _ = logforth::builder() 54 | .dispatch(|d| d.append(append::Stderr::default())) 55 | .try_apply(); 56 | 57 | let initial_delay = Some(Duration::from_secs(1)); 58 | let shutdown = Instant::now() + Duration::from_secs(10); 59 | 60 | MySimpleAction::new("schedule_with_fixed_delay").schedule_with_fixed_delay( 61 | MakeTokioDelay.delay_until(shutdown), 62 | &TokioSpawn, 63 | MakeTokioDelay, 64 | initial_delay, 65 | Duration::from_secs(2), 66 | ); 67 | 68 | MySimpleAction::new("schedule_at_fixed_rate").schedule_at_fixed_rate( 69 | MakeTokioDelay.delay_until(shutdown), 70 | &TokioSpawn, 71 | MakeTokioDelay, 72 | initial_delay, 73 | Duration::from_secs(2), 74 | ); 75 | 76 | MakeTokioDelay 77 | .delay_until(shutdown + Duration::from_secs(1)) 78 | .await; 79 | } 80 | -------------------------------------------------------------------------------- /licenserc.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | headerPath = "Apache-2.0.txt" 16 | 17 | includes = ['**/*.proto', '**/*.rs', '**/*.yml', '**/*.yaml', '**/*.toml'] 18 | 19 | [properties] 20 | copyrightOwner = "FastLabs Developers" 21 | inceptionYear = 2024 22 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [toolchain] 16 | channel = "stable" 17 | components = ["cargo", "rustfmt", "clippy", "rust-analyzer"] 18 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | comment_width = 120 16 | format_code_in_doc_comments = true 17 | group_imports = "StdExternalCrate" 18 | imports_granularity = "Item" 19 | wrap_comments = true 20 | -------------------------------------------------------------------------------- /taplo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | include = ["Cargo.toml", "**/*.toml"] 16 | 17 | [formatting] 18 | # Align consecutive entries vertically. 19 | align_entries = false 20 | # Append trailing commas for multi-line arrays. 21 | array_trailing_comma = true 22 | # Expand arrays to multiple lines that exceed the maximum column width. 23 | array_auto_expand = true 24 | # Collapse arrays that don't exceed the maximum column width and don't contain comments. 25 | array_auto_collapse = true 26 | # Omit white space padding from single-line arrays 27 | compact_arrays = true 28 | # Omit white space padding from the start and end of inline tables. 29 | compact_inline_tables = false 30 | # Maximum column width in characters, affects array expansion and collapse, this doesn't take whitespace into account. 31 | # Note that this is not set in stone, and works on a best-effort basis. 32 | column_width = 80 33 | # Indent based on tables and arrays of tables and their subtables, subtables out of order are not indented. 34 | indent_tables = false 35 | # The substring that is used for indentation, should be tabs or spaces (but technically can be anything). 36 | indent_string = ' ' 37 | # Add trailing newline at the end of the file if not present. 38 | trailing_newline = true 39 | # Alphabetically reorder keys that are not separated by empty lines. 40 | reorder_keys = true 41 | # Maximum amount of allowed consecutive blank lines. This does not affect the whitespace at the end of the document, as it is always stripped. 42 | allowed_blank_lines = 1 43 | # Use CRLF for line endings. 44 | crlf = false 45 | -------------------------------------------------------------------------------- /typos.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [default.extend-words] 16 | 17 | [files] 18 | extend-exclude = [] 19 | -------------------------------------------------------------------------------- /xtask/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "x" 17 | publish = false 18 | 19 | edition.workspace = true 20 | homepage.workspace = true 21 | license.workspace = true 22 | readme.workspace = true 23 | repository.workspace = true 24 | rust-version.workspace = true 25 | 26 | [package.metadata.release] 27 | release = false 28 | 29 | [dependencies] 30 | clap = { version = "4.5.20", features = ["derive"] } 31 | which = { version = "7.0.0" } 32 | 33 | [lints] 34 | workspace = true 35 | -------------------------------------------------------------------------------- /xtask/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::process::Command as StdCommand; 16 | 17 | use clap::Parser; 18 | use clap::Subcommand; 19 | 20 | #[derive(Parser)] 21 | struct Command { 22 | #[clap(subcommand)] 23 | sub: SubCommand, 24 | } 25 | 26 | impl Command { 27 | fn run(self) { 28 | match self.sub { 29 | SubCommand::Build(cmd) => cmd.run(), 30 | SubCommand::Lint(cmd) => cmd.run(), 31 | SubCommand::Test(cmd) => cmd.run(), 32 | } 33 | } 34 | } 35 | 36 | #[derive(Subcommand)] 37 | enum SubCommand { 38 | #[clap(about = "Compile workspace packages.")] 39 | Build(CommandBuild), 40 | #[clap(about = "Run format and clippy checks.")] 41 | Lint(CommandLint), 42 | #[clap(about = "Run unit tests.")] 43 | Test(CommandTest), 44 | } 45 | 46 | #[derive(Parser)] 47 | struct CommandBuild { 48 | #[arg(long, help = "Assert that `Cargo.lock` will remain unchanged.")] 49 | locked: bool, 50 | } 51 | 52 | impl CommandBuild { 53 | fn run(self) { 54 | run_command(make_build_cmd(self.locked)); 55 | } 56 | } 57 | 58 | #[derive(Parser)] 59 | struct CommandTest { 60 | #[arg(long, help = "Run tests serially and do not capture output.")] 61 | no_capture: bool, 62 | } 63 | 64 | impl CommandTest { 65 | fn run(self) { 66 | run_command(make_test_cmd(self.no_capture, true, &[])); 67 | } 68 | } 69 | 70 | #[derive(Parser)] 71 | #[clap(name = "lint")] 72 | struct CommandLint { 73 | #[arg(long, help = "Automatically apply lint suggestions.")] 74 | fix: bool, 75 | } 76 | 77 | impl CommandLint { 78 | fn run(self) { 79 | run_command(make_clippy_cmd(self.fix)); 80 | run_command(make_format_cmd(self.fix)); 81 | run_command(make_taplo_cmd(self.fix)); 82 | run_command(make_typos_cmd()); 83 | run_command(make_hawkeye_cmd(self.fix)); 84 | } 85 | } 86 | 87 | fn find_command(cmd: &str) -> StdCommand { 88 | match which::which(cmd) { 89 | Ok(exe) => { 90 | let mut cmd = StdCommand::new(exe); 91 | cmd.current_dir(env!("CARGO_WORKSPACE_DIR")); 92 | cmd 93 | } 94 | Err(err) => { 95 | panic!("{cmd} not found: {err}"); 96 | } 97 | } 98 | } 99 | 100 | fn ensure_installed(bin: &str, crate_name: &str) { 101 | if which::which(bin).is_err() { 102 | let mut cmd = find_command("cargo"); 103 | cmd.args(["install", crate_name]); 104 | run_command(cmd); 105 | } 106 | } 107 | 108 | fn run_command(mut cmd: StdCommand) { 109 | println!("{cmd:?}"); 110 | let status = cmd.status().expect("failed to execute process"); 111 | assert!(status.success(), "command failed: {status}"); 112 | } 113 | 114 | fn make_build_cmd(locked: bool) -> StdCommand { 115 | let mut cmd = find_command("cargo"); 116 | cmd.args([ 117 | "build", 118 | "--workspace", 119 | "--all-features", 120 | "--tests", 121 | "--examples", 122 | "--benches", 123 | "--bins", 124 | ]); 125 | if locked { 126 | cmd.arg("--locked"); 127 | } 128 | cmd 129 | } 130 | 131 | fn make_test_cmd(no_capture: bool, default_features: bool, features: &[&str]) -> StdCommand { 132 | let mut cmd = find_command("cargo"); 133 | cmd.args(["test", "--workspace"]); 134 | if !default_features { 135 | cmd.arg("--no-default-features"); 136 | } 137 | if !features.is_empty() { 138 | cmd.args(["--features", features.join(",").as_str()]); 139 | } 140 | if no_capture { 141 | cmd.args(["--", "--nocapture"]); 142 | } 143 | cmd 144 | } 145 | 146 | fn make_format_cmd(fix: bool) -> StdCommand { 147 | let mut cmd = find_command("cargo"); 148 | cmd.args(["fmt", "--all"]); 149 | if !fix { 150 | cmd.arg("--check"); 151 | } 152 | cmd 153 | } 154 | 155 | fn make_clippy_cmd(fix: bool) -> StdCommand { 156 | let mut cmd = find_command("cargo"); 157 | cmd.args([ 158 | "clippy", 159 | "--tests", 160 | "--all-features", 161 | "--all-targets", 162 | "--workspace", 163 | ]); 164 | if fix { 165 | cmd.args(["--allow-staged", "--allow-dirty", "--fix"]); 166 | } else { 167 | cmd.args(["--", "-D", "warnings"]); 168 | } 169 | cmd 170 | } 171 | 172 | fn make_hawkeye_cmd(fix: bool) -> StdCommand { 173 | ensure_installed("hawkeye", "hawkeye"); 174 | let mut cmd = find_command("hawkeye"); 175 | if fix { 176 | cmd.args(["format", "--fail-if-updated=false"]); 177 | } else { 178 | cmd.args(["check"]); 179 | } 180 | cmd 181 | } 182 | 183 | fn make_typos_cmd() -> StdCommand { 184 | ensure_installed("typos", "typos-cli"); 185 | find_command("typos") 186 | } 187 | 188 | fn make_taplo_cmd(fix: bool) -> StdCommand { 189 | ensure_installed("taplo", "taplo-cli"); 190 | let mut cmd = find_command("taplo"); 191 | if fix { 192 | cmd.args(["format"]); 193 | } else { 194 | cmd.args(["format", "--check"]); 195 | } 196 | cmd 197 | } 198 | 199 | fn main() { 200 | let cmd = Command::parse(); 201 | cmd.run() 202 | } 203 | --------------------------------------------------------------------------------