JosephStoneCellAI commited on
Commit
7a21509
·
verified ·
1 Parent(s): d6bb390

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/.github/workflows/ci.yml +57 -0
  2. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/ascii_char.rs +1069 -0
  3. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/ascii_str.rs +1600 -0
  4. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/ascii_string.rs +1057 -0
  5. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/free_functions.rs +59 -0
  6. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/lib.rs +82 -0
  7. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/serialization/ascii_char.rs +89 -0
  8. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/serialization/ascii_str.rs +79 -0
  9. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/serialization/ascii_string.rs +149 -0
  10. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/serialization/mod.rs +3 -0
  11. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/benches/defer.rs +69 -0
  12. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/benches/flush.rs +52 -0
  13. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/benches/pin.rs +31 -0
  14. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/examples/sanitize.rs +66 -0
  15. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/atomic.rs +1702 -0
  16. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/collector.rs +464 -0
  17. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/default.rs +93 -0
  18. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/deferred.rs +146 -0
  19. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/epoch.rs +132 -0
  20. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/guard.rs +523 -0
  21. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/internal.rs +600 -0
  22. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/lib.rs +166 -0
  23. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/sync/list.rs +487 -0
  24. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/sync/mod.rs +7 -0
  25. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/sync/once_lock.rs +88 -0
  26. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/sync/queue.rs +468 -0
  27. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/tests/loom.rs +157 -0
  28. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/src/hex.rs +87 -0
  29. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/src/lib.rs +419 -0
  30. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/src/pkcs8.rs +356 -0
  31. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/src/serde.rs +121 -0
  32. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pkcs8-v1.der +0 -0
  33. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pkcs8-v1.pem +3 -0
  34. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pkcs8-v2.der +0 -0
  35. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pkcs8-v2.pem +5 -0
  36. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pubkey.der +0 -0
  37. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pubkey.pem +3 -0
  38. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/hex.rs +50 -0
  39. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/pkcs8.rs +86 -0
  40. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/serde.rs +62 -0
  41. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/env_logger-0.11.9/src/writer/mod.rs +190 -0
  42. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/env_logger-0.11.9/src/writer/target.rs +26 -0
  43. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/date.rs +0 -0
  44. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/datetime.rs +0 -0
  45. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/iso_week_date.rs +919 -0
  46. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/mod.rs +290 -0
  47. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/time.rs +0 -0
  48. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/weekday.rs +802 -0
  49. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/duration.rs +146 -0
  50. .cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/error/civil.rs +66 -0
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/.github/workflows/ci.yml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches:
7
+ - master
8
+
9
+ jobs:
10
+ test:
11
+ name: Test with Rust ${{ matrix.rust }}
12
+ runs-on: ubuntu-latest
13
+ strategy:
14
+ fail-fast: false
15
+ matrix:
16
+ rust: [1.41.1, stable, beta, nightly]
17
+ steps:
18
+ - uses: actions/checkout@v2
19
+ - uses: hecrj/setup-rust-action@v1
20
+ with:
21
+ rust-version: ${{ matrix.rust }}
22
+ - run: cargo test --verbose --all-features
23
+ - run: cargo test --verbose --no-default-features --features alloc
24
+ - run: cargo test --verbose --no-default-features
25
+
26
+ clippy:
27
+ name: Lint with Clippy
28
+ runs-on: ubuntu-latest
29
+ env:
30
+ RUSTFLAGS: -Dwarnings
31
+ steps:
32
+ - uses: actions/checkout@v2
33
+ - uses: hecrj/setup-rust-action@v1
34
+ with:
35
+ components: clippy
36
+ - run: cargo clippy --all-targets --verbose --no-default-features
37
+ - run: cargo clippy --all-targets --verbose --all-features
38
+
39
+ test-minimal:
40
+ name: Test minimal dependency version with Rust nightly
41
+ runs-on: ubuntu-latest
42
+ steps:
43
+ - uses: actions/checkout@v2
44
+ - uses: hecrj/setup-rust-action@v1
45
+ with:
46
+ rust-version: nightly
47
+ - run: cargo test -Zminimal-versions --verbose --all-features
48
+
49
+ miri:
50
+ name: Run tests under `miri` to check for UB
51
+ runs-on: ubuntu-latest
52
+ steps:
53
+ - uses: actions/checkout@v3
54
+ - uses: dtolnay/rust-toolchain@nightly
55
+ with:
56
+ components: miri
57
+ - run: cargo miri test --all-features
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/ascii_char.rs ADDED
@@ -0,0 +1,1069 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use core::cmp::Ordering;
2
+ use core::mem;
3
+ use core::{char, fmt};
4
+ #[cfg(feature = "std")]
5
+ use std::error::Error;
6
+
7
+ #[allow(non_camel_case_types)]
8
+ /// An ASCII character. It wraps a `u8`, with the highest bit always zero.
9
+ #[derive(Clone, PartialEq, PartialOrd, Ord, Eq, Hash, Copy)]
10
+ #[repr(u8)]
11
+ pub enum AsciiChar {
12
+ /// `'\0'`
13
+ Null = 0,
14
+ /// [Start Of Heading](http://en.wikipedia.org/wiki/Start_of_Heading)
15
+ SOH = 1,
16
+ /// [Start Of teXt](http://en.wikipedia.org/wiki/Start_of_Text)
17
+ SOX = 2,
18
+ /// [End of TeXt](http://en.wikipedia.org/wiki/End-of-Text_character)
19
+ ETX = 3,
20
+ /// [End Of Transmission](http://en.wikipedia.org/wiki/End-of-Transmission_character)
21
+ EOT = 4,
22
+ /// [Enquiry](http://en.wikipedia.org/wiki/Enquiry_character)
23
+ ENQ = 5,
24
+ /// [Acknowledgement](http://en.wikipedia.org/wiki/Acknowledge_character)
25
+ ACK = 6,
26
+ /// [bell / alarm / audible](http://en.wikipedia.org/wiki/Bell_character)
27
+ ///
28
+ /// `'\a'` is not recognized by Rust.
29
+ Bell = 7,
30
+ /// [Backspace](http://en.wikipedia.org/wiki/Backspace)
31
+ ///
32
+ /// `'\b'` is not recognized by Rust.
33
+ BackSpace = 8,
34
+ /// `'\t'`
35
+ Tab = 9,
36
+ /// `'\n'`
37
+ LineFeed = 10,
38
+ /// [Vertical tab](http://en.wikipedia.org/wiki/Vertical_Tab)
39
+ ///
40
+ /// `'\v'` is not recognized by Rust.
41
+ VT = 11,
42
+ /// [Form Feed](http://en.wikipedia.org/wiki/Form_Feed)
43
+ ///
44
+ /// `'\f'` is not recognized by Rust.
45
+ FF = 12,
46
+ /// `'\r'`
47
+ CarriageReturn = 13,
48
+ /// [Shift In](http://en.wikipedia.org/wiki/Shift_Out_and_Shift_In_characters)
49
+ SI = 14,
50
+ /// [Shift Out](http://en.wikipedia.org/wiki/Shift_Out_and_Shift_In_characters)
51
+ SO = 15,
52
+ /// [Data Link Escape](http://en.wikipedia.org/wiki/Data_Link_Escape)
53
+ DLE = 16,
54
+ /// [Device control 1, often XON](http://en.wikipedia.org/wiki/Device_Control_1)
55
+ DC1 = 17,
56
+ /// Device control 2
57
+ DC2 = 18,
58
+ /// Device control 3, Often XOFF
59
+ DC3 = 19,
60
+ /// Device control 4
61
+ DC4 = 20,
62
+ /// [Negative AcKnowledgement](http://en.wikipedia.org/wiki/Negative-acknowledge_character)
63
+ NAK = 21,
64
+ /// [Synchronous idle](http://en.wikipedia.org/wiki/Synchronous_Idle)
65
+ SYN = 22,
66
+ /// [End of Transmission Block](http://en.wikipedia.org/wiki/End-of-Transmission-Block_character)
67
+ ETB = 23,
68
+ /// [Cancel](http://en.wikipedia.org/wiki/Cancel_character)
69
+ CAN = 24,
70
+ /// [End of Medium](http://en.wikipedia.org/wiki/End_of_Medium)
71
+ EM = 25,
72
+ /// [Substitute](http://en.wikipedia.org/wiki/Substitute_character)
73
+ SUB = 26,
74
+ /// [Escape](http://en.wikipedia.org/wiki/Escape_character)
75
+ ///
76
+ /// `'\e'` is not recognized by Rust.
77
+ ESC = 27,
78
+ /// [File Separator](http://en.wikipedia.org/wiki/File_separator)
79
+ FS = 28,
80
+ /// [Group Separator](http://en.wikipedia.org/wiki/Group_separator)
81
+ GS = 29,
82
+ /// [Record Separator](http://en.wikipedia.org/wiki/Record_separator)
83
+ RS = 30,
84
+ /// [Unit Separator](http://en.wikipedia.org/wiki/Unit_separator)
85
+ US = 31,
86
+ /// `' '`
87
+ Space = 32,
88
+ /// `'!'`
89
+ Exclamation = 33,
90
+ /// `'"'`
91
+ Quotation = 34,
92
+ /// `'#'`
93
+ Hash = 35,
94
+ /// `'$'`
95
+ Dollar = 36,
96
+ /// `'%'`
97
+ Percent = 37,
98
+ /// `'&'`
99
+ Ampersand = 38,
100
+ /// `'\''`
101
+ Apostrophe = 39,
102
+ /// `'('`
103
+ ParenOpen = 40,
104
+ /// `')'`
105
+ ParenClose = 41,
106
+ /// `'*'`
107
+ Asterisk = 42,
108
+ /// `'+'`
109
+ Plus = 43,
110
+ /// `','`
111
+ Comma = 44,
112
+ /// `'-'`
113
+ Minus = 45,
114
+ /// `'.'`
115
+ Dot = 46,
116
+ /// `'/'`
117
+ Slash = 47,
118
+ /// `'0'`
119
+ _0 = 48,
120
+ /// `'1'`
121
+ _1 = 49,
122
+ /// `'2'`
123
+ _2 = 50,
124
+ /// `'3'`
125
+ _3 = 51,
126
+ /// `'4'`
127
+ _4 = 52,
128
+ /// `'5'`
129
+ _5 = 53,
130
+ /// `'6'`
131
+ _6 = 54,
132
+ /// `'7'`
133
+ _7 = 55,
134
+ /// `'8'`
135
+ _8 = 56,
136
+ /// `'9'`
137
+ _9 = 57,
138
+ /// `':'`
139
+ Colon = 58,
140
+ /// `';'`
141
+ Semicolon = 59,
142
+ /// `'<'`
143
+ LessThan = 60,
144
+ /// `'='`
145
+ Equal = 61,
146
+ /// `'>'`
147
+ GreaterThan = 62,
148
+ /// `'?'`
149
+ Question = 63,
150
+ /// `'@'`
151
+ At = 64,
152
+ /// `'A'`
153
+ A = 65,
154
+ /// `'B'`
155
+ B = 66,
156
+ /// `'C'`
157
+ C = 67,
158
+ /// `'D'`
159
+ D = 68,
160
+ /// `'E'`
161
+ E = 69,
162
+ /// `'F'`
163
+ F = 70,
164
+ /// `'G'`
165
+ G = 71,
166
+ /// `'H'`
167
+ H = 72,
168
+ /// `'I'`
169
+ I = 73,
170
+ /// `'J'`
171
+ J = 74,
172
+ /// `'K'`
173
+ K = 75,
174
+ /// `'L'`
175
+ L = 76,
176
+ /// `'M'`
177
+ M = 77,
178
+ /// `'N'`
179
+ N = 78,
180
+ /// `'O'`
181
+ O = 79,
182
+ /// `'P'`
183
+ P = 80,
184
+ /// `'Q'`
185
+ Q = 81,
186
+ /// `'R'`
187
+ R = 82,
188
+ /// `'S'`
189
+ S = 83,
190
+ /// `'T'`
191
+ T = 84,
192
+ /// `'U'`
193
+ U = 85,
194
+ /// `'V'`
195
+ V = 86,
196
+ /// `'W'`
197
+ W = 87,
198
+ /// `'X'`
199
+ X = 88,
200
+ /// `'Y'`
201
+ Y = 89,
202
+ /// `'Z'`
203
+ Z = 90,
204
+ /// `'['`
205
+ BracketOpen = 91,
206
+ /// `'\'`
207
+ BackSlash = 92,
208
+ /// `']'`
209
+ BracketClose = 93,
210
+ /// `'^'`
211
+ Caret = 94,
212
+ /// `'_'`
213
+ UnderScore = 95,
214
+ /// `'`'`
215
+ Grave = 96,
216
+ /// `'a'`
217
+ a = 97,
218
+ /// `'b'`
219
+ b = 98,
220
+ /// `'c'`
221
+ c = 99,
222
+ /// `'d'`
223
+ d = 100,
224
+ /// `'e'`
225
+ e = 101,
226
+ /// `'f'`
227
+ f = 102,
228
+ /// `'g'`
229
+ g = 103,
230
+ /// `'h'`
231
+ h = 104,
232
+ /// `'i'`
233
+ i = 105,
234
+ /// `'j'`
235
+ j = 106,
236
+ /// `'k'`
237
+ k = 107,
238
+ /// `'l'`
239
+ l = 108,
240
+ /// `'m'`
241
+ m = 109,
242
+ /// `'n'`
243
+ n = 110,
244
+ /// `'o'`
245
+ o = 111,
246
+ /// `'p'`
247
+ p = 112,
248
+ /// `'q'`
249
+ q = 113,
250
+ /// `'r'`
251
+ r = 114,
252
+ /// `'s'`
253
+ s = 115,
254
+ /// `'t'`
255
+ t = 116,
256
+ /// `'u'`
257
+ u = 117,
258
+ /// `'v'`
259
+ v = 118,
260
+ /// `'w'`
261
+ w = 119,
262
+ /// `'x'`
263
+ x = 120,
264
+ /// `'y'`
265
+ y = 121,
266
+ /// `'z'`
267
+ z = 122,
268
+ /// `'{'`
269
+ CurlyBraceOpen = 123,
270
+ /// `'|'`
271
+ VerticalBar = 124,
272
+ /// `'}'`
273
+ CurlyBraceClose = 125,
274
+ /// `'~'`
275
+ Tilde = 126,
276
+ /// [Delete](http://en.wikipedia.org/wiki/Delete_character)
277
+ DEL = 127,
278
+ }
279
+
280
+ impl AsciiChar {
281
+ /// Constructs an ASCII character from a `u8`, `char` or other character type.
282
+ ///
283
+ /// # Errors
284
+ /// Returns `Err(())` if the character can't be ASCII encoded.
285
+ ///
286
+ /// # Example
287
+ /// ```
288
+ /// # use ascii::AsciiChar;
289
+ /// let a = AsciiChar::from_ascii('g').unwrap();
290
+ /// assert_eq!(a.as_char(), 'g');
291
+ /// ```
292
+ #[inline]
293
+ pub fn from_ascii<C: ToAsciiChar>(ch: C) -> Result<Self, ToAsciiCharError> {
294
+ ch.to_ascii_char()
295
+ }
296
+
297
+ /// Create an `AsciiChar` from a `char`, panicking if it's not ASCII.
298
+ ///
299
+ /// This function is intended for creating `AsciiChar` values from
300
+ /// hardcoded known-good character literals such as `'K'`, `'-'` or `'\0'`,
301
+ /// and for use in `const` contexts.
302
+ /// Use [`from_ascii()`](#method.from_ascii) instead when you're not
303
+ /// certain the character is ASCII.
304
+ ///
305
+ /// # Examples
306
+ ///
307
+ /// ```
308
+ /// # use ascii::AsciiChar;
309
+ /// assert_eq!(AsciiChar::new('@'), AsciiChar::At);
310
+ /// assert_eq!(AsciiChar::new('C').as_char(), 'C');
311
+ /// ```
312
+ ///
313
+ /// In a constant:
314
+ /// ```
315
+ /// # use ascii::AsciiChar;
316
+ /// const SPLIT_ON: AsciiChar = AsciiChar::new(',');
317
+ /// ```
318
+ ///
319
+ /// This will not compile:
320
+ /// ```compile_fail
321
+ /// # use ascii::AsciiChar;
322
+ /// const BAD: AsciiChar = AsciiChar::new('Ø');
323
+ /// ```
324
+ ///
325
+ /// # Panics
326
+ ///
327
+ /// This function will panic if passed a non-ASCII character.
328
+ ///
329
+ /// The panic message might not be the most descriptive due to the
330
+ /// current limitations of `const fn`.
331
+ #[must_use]
332
+ pub const fn new(ch: char) -> AsciiChar {
333
+ // It's restricted to this function, and without it
334
+ // we'd need to specify `AsciiChar::` or `Self::` 128 times.
335
+ #[allow(clippy::enum_glob_use)]
336
+ use AsciiChar::*;
337
+
338
+ #[rustfmt::skip]
339
+ const ALL: [AsciiChar; 128] = [
340
+ Null, SOH, SOX, ETX, EOT, ENQ, ACK, Bell,
341
+ BackSpace, Tab, LineFeed, VT, FF, CarriageReturn, SI, SO,
342
+ DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB,
343
+ CAN, EM, SUB, ESC, FS, GS, RS, US,
344
+ Space, Exclamation, Quotation, Hash, Dollar, Percent, Ampersand, Apostrophe,
345
+ ParenOpen, ParenClose, Asterisk, Plus, Comma, Minus, Dot, Slash,
346
+ _0, _1, _2, _3, _4, _5, _6, _7,
347
+ _8, _9, Colon, Semicolon, LessThan, Equal, GreaterThan, Question,
348
+ At, A, B, C, D, E, F, G,
349
+ H, I, J, K, L, M, N, O,
350
+ P, Q, R, S, T, U, V, W,
351
+ X, Y, Z, BracketOpen, BackSlash, BracketClose, Caret, UnderScore,
352
+ Grave, a, b, c, d, e, f, g,
353
+ h, i, j, k, l, m, n, o,
354
+ p, q, r, s, t, u, v, w,
355
+ x, y, z, CurlyBraceOpen, VerticalBar, CurlyBraceClose, Tilde, DEL,
356
+ ];
357
+
358
+ // We want to slice here and detect `const_err` from rustc if the slice is invalid
359
+ #[allow(clippy::indexing_slicing)]
360
+ ALL[ch as usize]
361
+ }
362
+
363
+ /// Constructs an ASCII character from a `u8`, `char` or other character
364
+ /// type without any checks.
365
+ ///
366
+ /// # Safety
367
+ ///
368
+ /// This function is very unsafe as it can create invalid enum
369
+ /// discriminants, which instantly creates undefined behavior.
370
+ /// (`let _ = AsciiChar::from_ascii_unchecked(200);` alone is UB).
371
+ ///
372
+ /// The undefined behavior is not just theoretical either:
373
+ /// For example, `[0; 128][AsciiChar::from_ascii_unchecked(255) as u8 as usize] = 0`
374
+ /// might not panic, creating a buffer overflow,
375
+ /// and `Some(AsciiChar::from_ascii_unchecked(128))` might be `None`.
376
+ #[inline]
377
+ #[must_use]
378
+ pub unsafe fn from_ascii_unchecked(ch: u8) -> Self {
379
+ // SAFETY: Caller guarantees `ch` is within bounds of ascii.
380
+ unsafe { ch.to_ascii_char_unchecked() }
381
+ }
382
+
383
+ /// Converts an ASCII character into a `u8`.
384
+ #[inline]
385
+ #[must_use]
386
+ pub const fn as_byte(self) -> u8 {
387
+ self as u8
388
+ }
389
+
390
+ /// Converts an ASCII character into a `char`.
391
+ #[inline]
392
+ #[must_use]
393
+ pub const fn as_char(self) -> char {
394
+ self as u8 as char
395
+ }
396
+
397
+ // the following methods are like ctype, and the implementation is inspired by musl.
398
+ // The ascii_ methods take self by reference for maximum compatibility
399
+ // with the corresponding methods on u8 and char.
400
+ // It is bad for both usability and performance, but marking those
401
+ // that doesn't have a non-ascii sibling #[inline] should
402
+ // make the compiler optimize away the indirection.
403
+
404
+ /// Turns uppercase into lowercase, but also modifies '@' and '<'..='_'
405
+ #[must_use]
406
+ const fn to_not_upper(self) -> u8 {
407
+ self as u8 | 0b010_0000
408
+ }
409
+
410
+ /// Check if the character is a letter (a-z, A-Z)
411
+ #[inline]
412
+ #[must_use]
413
+ pub const fn is_alphabetic(self) -> bool {
414
+ (self.to_not_upper() >= b'a') & (self.to_not_upper() <= b'z')
415
+ }
416
+
417
+ /// Check if the character is a letter (a-z, A-Z).
418
+ ///
419
+ /// This method is identical to [`is_alphabetic()`](#method.is_alphabetic)
420
+ #[inline]
421
+ #[must_use]
422
+ pub const fn is_ascii_alphabetic(&self) -> bool {
423
+ self.is_alphabetic()
424
+ }
425
+
426
+ /// Check if the character is a digit in the given radix.
427
+ ///
428
+ /// If the radix is always 10 or 16,
429
+ /// [`is_ascii_digit()`](#method.is_ascii_digit) and
430
+ /// [`is_ascii_hexdigit()`](#method.is_ascii_hexdigit()) will be faster.
431
+ ///
432
+ /// # Panics
433
+ ///
434
+ /// Radixes greater than 36 are not supported and will result in a panic.
435
+ #[must_use]
436
+ pub fn is_digit(self, radix: u32) -> bool {
437
+ match (self as u8, radix) {
438
+ (b'0'..=b'9', 0..=36) => u32::from(self as u8 - b'0') < radix,
439
+ (b'a'..=b'z', 11..=36) => u32::from(self as u8 - b'a') < radix - 10,
440
+ (b'A'..=b'Z', 11..=36) => u32::from(self as u8 - b'A') < radix - 10,
441
+ (_, 0..=36) => false,
442
+ (_, _) => panic!("radixes greater than 36 are not supported"),
443
+ }
444
+ }
445
+
446
+ /// Check if the character is a number (0-9)
447
+ ///
448
+ /// # Examples
449
+ /// ```
450
+ /// # use ascii::AsciiChar;
451
+ /// assert_eq!(AsciiChar::new('0').is_ascii_digit(), true);
452
+ /// assert_eq!(AsciiChar::new('9').is_ascii_digit(), true);
453
+ /// assert_eq!(AsciiChar::new('a').is_ascii_digit(), false);
454
+ /// assert_eq!(AsciiChar::new('A').is_ascii_digit(), false);
455
+ /// assert_eq!(AsciiChar::new('/').is_ascii_digit(), false);
456
+ /// ```
457
+ #[inline]
458
+ #[must_use]
459
+ pub const fn is_ascii_digit(&self) -> bool {
460
+ (*self as u8 >= b'0') & (*self as u8 <= b'9')
461
+ }
462
+
463
+ /// Check if the character is a letter or number
464
+ #[inline]
465
+ #[must_use]
466
+ pub const fn is_alphanumeric(self) -> bool {
467
+ self.is_alphabetic() | self.is_ascii_digit()
468
+ }
469
+
470
+ /// Check if the character is a letter or number
471
+ ///
472
+ /// This method is identical to [`is_alphanumeric()`](#method.is_alphanumeric)
473
+ #[inline]
474
+ #[must_use]
475
+ pub const fn is_ascii_alphanumeric(&self) -> bool {
476
+ self.is_alphanumeric()
477
+ }
478
+
479
+ /// Check if the character is a space or horizontal tab
480
+ ///
481
+ /// # Examples
482
+ /// ```
483
+ /// # use ascii::AsciiChar;
484
+ /// assert!(AsciiChar::Space.is_ascii_blank());
485
+ /// assert!(AsciiChar::Tab.is_ascii_blank());
486
+ /// assert!(!AsciiChar::VT.is_ascii_blank());
487
+ /// assert!(!AsciiChar::LineFeed.is_ascii_blank());
488
+ /// assert!(!AsciiChar::CarriageReturn.is_ascii_blank());
489
+ /// assert!(!AsciiChar::FF.is_ascii_blank());
490
+ /// ```
491
+ #[inline]
492
+ #[must_use]
493
+ pub const fn is_ascii_blank(&self) -> bool {
494
+ (*self as u8 == b' ') | (*self as u8 == b'\t')
495
+ }
496
+
497
+ /// Check if the character one of ' ', '\t', '\n', '\r',
498
+ /// '\0xb' (vertical tab) or '\0xc' (form feed).
499
+ #[inline]
500
+ #[must_use]
501
+ pub const fn is_whitespace(self) -> bool {
502
+ let b = self as u8;
503
+ self.is_ascii_blank() | (b == b'\n') | (b == b'\r') | (b == 0x0b) | (b == 0x0c)
504
+ }
505
+
506
+ /// Check if the character is a ' ', '\t', '\n', '\r' or '\0xc' (form feed).
507
+ ///
508
+ /// This method is NOT identical to `is_whitespace()`.
509
+ #[inline]
510
+ #[must_use]
511
+ pub const fn is_ascii_whitespace(&self) -> bool {
512
+ self.is_ascii_blank()
513
+ | (*self as u8 == b'\n')
514
+ | (*self as u8 == b'\r')
515
+ | (*self as u8 == 0x0c/*form feed*/)
516
+ }
517
+
518
+ /// Check if the character is a control character
519
+ ///
520
+ /// # Examples
521
+ /// ```
522
+ /// # use ascii::AsciiChar;
523
+ /// assert_eq!(AsciiChar::new('\0').is_ascii_control(), true);
524
+ /// assert_eq!(AsciiChar::new('n').is_ascii_control(), false);
525
+ /// assert_eq!(AsciiChar::new(' ').is_ascii_control(), false);
526
+ /// assert_eq!(AsciiChar::new('\n').is_ascii_control(), true);
527
+ /// assert_eq!(AsciiChar::new('\t').is_ascii_control(), true);
528
+ /// assert_eq!(AsciiChar::EOT.is_ascii_control(), true);
529
+ /// ```
530
+ #[inline]
531
+ #[must_use]
532
+ pub const fn is_ascii_control(&self) -> bool {
533
+ ((*self as u8) < b' ') | (*self as u8 == 127)
534
+ }
535
+
536
+ /// Checks if the character is printable (except space)
537
+ ///
538
+ /// # Examples
539
+ /// ```
540
+ /// # use ascii::AsciiChar;
541
+ /// assert_eq!(AsciiChar::new('n').is_ascii_graphic(), true);
542
+ /// assert_eq!(AsciiChar::new(' ').is_ascii_graphic(), false);
543
+ /// assert_eq!(AsciiChar::new('\n').is_ascii_graphic(), false);
544
+ /// ```
545
+ #[inline]
546
+ #[must_use]
547
+ pub const fn is_ascii_graphic(&self) -> bool {
548
+ self.as_byte().wrapping_sub(b' ' + 1) < 0x5E
549
+ }
550
+
551
+ /// Checks if the character is printable (including space)
552
+ ///
553
+ /// # Examples
554
+ /// ```
555
+ /// # use ascii::AsciiChar;
556
+ /// assert_eq!(AsciiChar::new('n').is_ascii_printable(), true);
557
+ /// assert_eq!(AsciiChar::new(' ').is_ascii_printable(), true);
558
+ /// assert_eq!(AsciiChar::new('\n').is_ascii_printable(), false);
559
+ /// ```
560
+ #[inline]
561
+ #[must_use]
562
+ pub const fn is_ascii_printable(&self) -> bool {
563
+ self.as_byte().wrapping_sub(b' ') < 0x5F
564
+ }
565
+
566
+ /// Checks if the character is alphabetic and lowercase (a-z).
567
+ ///
568
+ /// # Examples
569
+ /// ```
570
+ /// use ascii::AsciiChar;
571
+ /// assert_eq!(AsciiChar::new('a').is_lowercase(), true);
572
+ /// assert_eq!(AsciiChar::new('A').is_lowercase(), false);
573
+ /// assert_eq!(AsciiChar::new('@').is_lowercase(), false);
574
+ /// ```
575
+ #[inline]
576
+ #[must_use]
577
+ pub const fn is_lowercase(self) -> bool {
578
+ self.as_byte().wrapping_sub(b'a') < 26
579
+ }
580
+
581
+ /// Checks if the character is alphabetic and lowercase (a-z).
582
+ ///
583
+ /// This method is identical to [`is_lowercase()`](#method.is_lowercase)
584
+ #[inline]
585
+ #[must_use]
586
+ pub const fn is_ascii_lowercase(&self) -> bool {
587
+ self.is_lowercase()
588
+ }
589
+
590
+ /// Checks if the character is alphabetic and uppercase (A-Z).
591
+ ///
592
+ /// # Examples
593
+ /// ```
594
+ /// # use ascii::AsciiChar;
595
+ /// assert_eq!(AsciiChar::new('A').is_uppercase(), true);
596
+ /// assert_eq!(AsciiChar::new('a').is_uppercase(), false);
597
+ /// assert_eq!(AsciiChar::new('@').is_uppercase(), false);
598
+ /// ```
599
+ #[inline]
600
+ #[must_use]
601
+ pub const fn is_uppercase(self) -> bool {
602
+ self.as_byte().wrapping_sub(b'A') < 26
603
+ }
604
+
605
+ /// Checks if the character is alphabetic and uppercase (A-Z).
606
+ ///
607
+ /// This method is identical to [`is_uppercase()`](#method.is_uppercase)
608
+ #[inline]
609
+ #[must_use]
610
+ pub const fn is_ascii_uppercase(&self) -> bool {
611
+ self.is_uppercase()
612
+ }
613
+
614
+ /// Checks if the character is punctuation
615
+ ///
616
+ /// # Examples
617
+ /// ```
618
+ /// # use ascii::AsciiChar;
619
+ /// assert_eq!(AsciiChar::new('n').is_ascii_punctuation(), false);
620
+ /// assert_eq!(AsciiChar::new(' ').is_ascii_punctuation(), false);
621
+ /// assert_eq!(AsciiChar::new('_').is_ascii_punctuation(), true);
622
+ /// assert_eq!(AsciiChar::new('~').is_ascii_punctuation(), true);
623
+ /// ```
624
+ #[inline]
625
+ #[must_use]
626
+ pub const fn is_ascii_punctuation(&self) -> bool {
627
+ self.is_ascii_graphic() & !self.is_alphanumeric()
628
+ }
629
+
630
+ /// Checks if the character is a valid hex digit
631
+ ///
632
+ /// # Examples
633
+ /// ```
634
+ /// # use ascii::AsciiChar;
635
+ /// assert_eq!(AsciiChar::new('5').is_ascii_hexdigit(), true);
636
+ /// assert_eq!(AsciiChar::new('a').is_ascii_hexdigit(), true);
637
+ /// assert_eq!(AsciiChar::new('F').is_ascii_hexdigit(), true);
638
+ /// assert_eq!(AsciiChar::new('G').is_ascii_hexdigit(), false);
639
+ /// assert_eq!(AsciiChar::new(' ').is_ascii_hexdigit(), false);
640
+ /// ```
641
+ #[inline]
642
+ #[must_use]
643
+ pub const fn is_ascii_hexdigit(&self) -> bool {
644
+ self.is_ascii_digit() | ((*self as u8 | 0x20_u8).wrapping_sub(b'a') < 6)
645
+ }
646
+
647
+ /// Unicode has printable versions of the ASCII control codes, like '␛'.
648
+ ///
649
+ /// This function is identical with `.as_char()`
650
+ /// for all values `.is_printable()` returns true for,
651
+ /// but replaces the control codes with those unicodes printable versions.
652
+ ///
653
+ /// # Examples
654
+ /// ```
655
+ /// # use ascii::AsciiChar;
656
+ /// assert_eq!(AsciiChar::new('\0').as_printable_char(), '␀');
657
+ /// assert_eq!(AsciiChar::new('\n').as_printable_char(), '␊');
658
+ /// assert_eq!(AsciiChar::new(' ').as_printable_char(), ' ');
659
+ /// assert_eq!(AsciiChar::new('p').as_printable_char(), 'p');
660
+ /// ```
661
+ #[must_use]
662
+ pub fn as_printable_char(self) -> char {
663
+ match self as u8 {
664
+ // Non printable characters
665
+ // SAFETY: From codepoint 0x2400 ('␀') to 0x241f (`␟`), there are characters representing
666
+ // the unprintable characters from 0x0 to 0x1f, ordered correctly.
667
+ // As `b` is guaranteed to be within 0x0 to 0x1f, the conversion represents a
668
+ // valid character.
669
+ b @ 0x0..=0x1f => unsafe { char::from_u32_unchecked(u32::from('␀') + u32::from(b)) },
670
+
671
+ // 0x7f (delete) has it's own character at codepoint 0x2420, not 0x247f, so it is special
672
+ // cased to return it's character
673
+ 0x7f => '␡',
674
+
675
+ // All other characters are printable, and per function contract use `Self::as_char`
676
+ _ => self.as_char(),
677
+ }
678
+ }
679
+
680
+ /// Replaces letters `a` to `z` with `A` to `Z`
681
+ pub fn make_ascii_uppercase(&mut self) {
682
+ *self = self.to_ascii_uppercase();
683
+ }
684
+
685
+ /// Replaces letters `A` to `Z` with `a` to `z`
686
+ pub fn make_ascii_lowercase(&mut self) {
687
+ *self = self.to_ascii_lowercase();
688
+ }
689
+
690
+ /// Maps letters a-z to A-Z and returns any other character unchanged.
691
+ ///
692
+ /// # Examples
693
+ /// ```
694
+ /// # use ascii::AsciiChar;
695
+ /// assert_eq!(AsciiChar::new('u').to_ascii_uppercase().as_char(), 'U');
696
+ /// assert_eq!(AsciiChar::new('U').to_ascii_uppercase().as_char(), 'U');
697
+ /// assert_eq!(AsciiChar::new('2').to_ascii_uppercase().as_char(), '2');
698
+ /// assert_eq!(AsciiChar::new('=').to_ascii_uppercase().as_char(), '=');
699
+ /// assert_eq!(AsciiChar::new('[').to_ascii_uppercase().as_char(), '[');
700
+ /// ```
701
+ #[inline]
702
+ #[must_use]
703
+ #[allow(clippy::indexing_slicing)] // We're sure it'll either access one or the other, as `bool` is either `0` or `1`
704
+ pub const fn to_ascii_uppercase(&self) -> Self {
705
+ [*self, AsciiChar::new((*self as u8 & 0b101_1111) as char)][self.is_lowercase() as usize]
706
+ }
707
+
708
+ /// Maps letters A-Z to a-z and returns any other character unchanged.
709
+ ///
710
+ /// # Examples
711
+ /// ```
712
+ /// # use ascii::AsciiChar;
713
+ /// assert_eq!(AsciiChar::new('U').to_ascii_lowercase().as_char(), 'u');
714
+ /// assert_eq!(AsciiChar::new('u').to_ascii_lowercase().as_char(), 'u');
715
+ /// assert_eq!(AsciiChar::new('2').to_ascii_lowercase().as_char(), '2');
716
+ /// assert_eq!(AsciiChar::new('^').to_ascii_lowercase().as_char(), '^');
717
+ /// assert_eq!(AsciiChar::new('\x7f').to_ascii_lowercase().as_char(), '\x7f');
718
+ /// ```
719
+ #[inline]
720
+ #[must_use]
721
+ #[allow(clippy::indexing_slicing)] // We're sure it'll either access one or the other, as `bool` is either `0` or `1`
722
+ pub const fn to_ascii_lowercase(&self) -> Self {
723
+ [*self, AsciiChar::new(self.to_not_upper() as char)][self.is_uppercase() as usize]
724
+ }
725
+
726
+ /// Compares two characters case-insensitively.
727
+ #[inline]
728
+ #[must_use]
729
+ pub const fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
730
+ (self.as_byte() == other.as_byte())
731
+ | (self.is_alphabetic() & (self.to_not_upper() == other.to_not_upper()))
732
+ }
733
+ }
734
+
735
+ impl fmt::Display for AsciiChar {
736
+ #[inline]
737
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
738
+ self.as_char().fmt(f)
739
+ }
740
+ }
741
+
742
+ impl fmt::Debug for AsciiChar {
743
+ #[inline]
744
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
745
+ self.as_char().fmt(f)
746
+ }
747
+ }
748
+
749
+ impl Default for AsciiChar {
750
+ fn default() -> AsciiChar {
751
+ AsciiChar::Null
752
+ }
753
+ }
754
+
755
+ macro_rules! impl_into_partial_eq_ord {
756
+ ($wider:ty, $to_wider:expr) => {
757
+ impl From<AsciiChar> for $wider {
758
+ #[inline]
759
+ fn from(a: AsciiChar) -> $wider {
760
+ $to_wider(a)
761
+ }
762
+ }
763
+ impl PartialEq<$wider> for AsciiChar {
764
+ #[inline]
765
+ fn eq(&self, rhs: &$wider) -> bool {
766
+ $to_wider(*self) == *rhs
767
+ }
768
+ }
769
+ impl PartialEq<AsciiChar> for $wider {
770
+ #[inline]
771
+ fn eq(&self, rhs: &AsciiChar) -> bool {
772
+ *self == $to_wider(*rhs)
773
+ }
774
+ }
775
+ impl PartialOrd<$wider> for AsciiChar {
776
+ #[inline]
777
+ fn partial_cmp(&self, rhs: &$wider) -> Option<Ordering> {
778
+ $to_wider(*self).partial_cmp(rhs)
779
+ }
780
+ }
781
+ impl PartialOrd<AsciiChar> for $wider {
782
+ #[inline]
783
+ fn partial_cmp(&self, rhs: &AsciiChar) -> Option<Ordering> {
784
+ self.partial_cmp(&$to_wider(*rhs))
785
+ }
786
+ }
787
+ };
788
+ }
789
+ impl_into_partial_eq_ord! {u8, AsciiChar::as_byte}
790
+ impl_into_partial_eq_ord! {char, AsciiChar::as_char}
791
+
792
+ /// Error returned by `ToAsciiChar`.
793
+ #[derive(Clone, Copy, PartialEq, Eq)]
794
+ pub struct ToAsciiCharError(());
795
+
796
+ const ERRORMSG_CHAR: &str = "not an ASCII character";
797
+
798
+ #[cfg(not(feature = "std"))]
799
+ impl ToAsciiCharError {
800
+ /// Returns a description for this error, like `std::error::Error::description`.
801
+ #[inline]
802
+ #[must_use]
803
+ #[allow(clippy::unused_self)]
804
+ pub const fn description(&self) -> &'static str {
805
+ ERRORMSG_CHAR
806
+ }
807
+ }
808
+
809
+ impl fmt::Debug for ToAsciiCharError {
810
+ fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
811
+ write!(fmtr, "{}", ERRORMSG_CHAR)
812
+ }
813
+ }
814
+
815
+ impl fmt::Display for ToAsciiCharError {
816
+ fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
817
+ write!(fmtr, "{}", ERRORMSG_CHAR)
818
+ }
819
+ }
820
+
821
+ #[cfg(feature = "std")]
822
+ impl Error for ToAsciiCharError {
823
+ #[inline]
824
+ fn description(&self) -> &'static str {
825
+ ERRORMSG_CHAR
826
+ }
827
+ }
828
+
829
+ /// Convert `char`, `u8` and other character types to `AsciiChar`.
830
+ pub trait ToAsciiChar {
831
+ /// Convert to `AsciiChar`.
832
+ ///
833
+ /// # Errors
834
+ /// If `self` is outside the valid ascii range, this returns `Err`
835
+ fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError>;
836
+
837
+ /// Convert to `AsciiChar` without checking that it is an ASCII character.
838
+ ///
839
+ /// # Safety
840
+ /// Calling this function with a value outside of the ascii range, `0x0` to `0x7f` inclusive,
841
+ /// is undefined behavior.
842
+ // TODO: Make sure this is the contract we want to express in this function.
843
+ // It is ambigous if numbers such as `0xffffff20_u32` are valid ascii characters,
844
+ // as this function returns `Ascii::Space` due to the cast to `u8`, even though
845
+ // `to_ascii_char` returns `Err()`.
846
+ unsafe fn to_ascii_char_unchecked(self) -> AsciiChar;
847
+ }
848
+
849
+ impl ToAsciiChar for AsciiChar {
850
+ #[inline]
851
+ fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
852
+ Ok(self)
853
+ }
854
+
855
+ #[inline]
856
+ unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
857
+ self
858
+ }
859
+ }
860
+
861
+ impl ToAsciiChar for u8 {
862
+ #[inline]
863
+ fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
864
+ u32::from(self).to_ascii_char()
865
+ }
866
+ #[inline]
867
+ unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
868
+ // SAFETY: Caller guarantees `self` is within bounds of the enum
869
+ // variants, so this cast successfully produces a valid ascii
870
+ // variant
871
+ unsafe { mem::transmute::<u8, AsciiChar>(self) }
872
+ }
873
+ }
874
+
875
+ // Note: Casts to `u8` here does not cause problems, as the negative
876
+ // range is mapped outside of ascii bounds and we don't mind losing
877
+ // the sign, as long as negative numbers are mapped outside ascii range.
878
+ #[allow(clippy::cast_sign_loss)]
879
+ impl ToAsciiChar for i8 {
880
+ #[inline]
881
+ fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
882
+ u32::from(self as u8).to_ascii_char()
883
+ }
884
+ #[inline]
885
+ unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
886
+ // SAFETY: Caller guarantees `self` is within bounds of the enum
887
+ // variants, so this cast successfully produces a valid ascii
888
+ // variant
889
+ unsafe { mem::transmute::<u8, AsciiChar>(self as u8) }
890
+ }
891
+ }
892
+
893
+ impl ToAsciiChar for char {
894
+ #[inline]
895
+ fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
896
+ u32::from(self).to_ascii_char()
897
+ }
898
+ #[inline]
899
+ unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
900
+ // SAFETY: Caller guarantees we're within ascii range.
901
+ unsafe { u32::from(self).to_ascii_char_unchecked() }
902
+ }
903
+ }
904
+
905
+ impl ToAsciiChar for u32 {
906
+ fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
907
+ match self {
908
+ // SAFETY: We're within the valid ascii range in this branch.
909
+ 0x0..=0x7f => Ok(unsafe { self.to_ascii_char_unchecked() }),
910
+ _ => Err(ToAsciiCharError(())),
911
+ }
912
+ }
913
+
914
+ #[inline]
915
+ unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
916
+ // Note: This cast discards the top bytes, this may cause problems, see
917
+ // the TODO on this method's documentation in the trait.
918
+ // SAFETY: Caller guarantees we're within ascii range.
919
+ #[allow(clippy::cast_possible_truncation)] // We want to truncate it
920
+ unsafe {
921
+ (self as u8).to_ascii_char_unchecked()
922
+ }
923
+ }
924
+ }
925
+
926
+ impl ToAsciiChar for u16 {
927
+ fn to_ascii_char(self) -> Result<AsciiChar, ToAsciiCharError> {
928
+ u32::from(self).to_ascii_char()
929
+ }
930
+ #[inline]
931
+ unsafe fn to_ascii_char_unchecked(self) -> AsciiChar {
932
+ // Note: This cast discards the top bytes, this may cause problems, see
933
+ // the TODO on this method's documentation in the trait.
934
+ // SAFETY: Caller guarantees we're within ascii range.
935
+ #[allow(clippy::cast_possible_truncation)] // We want to truncate it
936
+ unsafe {
937
+ (self as u8).to_ascii_char_unchecked()
938
+ }
939
+ }
940
+ }
941
+
942
+ #[cfg(test)]
943
+ mod tests {
944
+ use super::{AsciiChar, ToAsciiChar, ToAsciiCharError};
945
+
946
+ #[test]
947
+ fn to_ascii_char() {
948
+ fn generic<C: ToAsciiChar>(ch: C) -> Result<AsciiChar, ToAsciiCharError> {
949
+ ch.to_ascii_char()
950
+ }
951
+ assert_eq!(generic(AsciiChar::A), Ok(AsciiChar::A));
952
+ assert_eq!(generic(b'A'), Ok(AsciiChar::A));
953
+ assert_eq!(generic('A'), Ok(AsciiChar::A));
954
+ assert!(generic(200_u16).is_err());
955
+ assert!(generic('λ').is_err());
956
+ }
957
+
958
+ #[test]
959
+ fn as_byte_and_char() {
960
+ assert_eq!(AsciiChar::A.as_byte(), b'A');
961
+ assert_eq!(AsciiChar::A.as_char(), 'A');
962
+ }
963
+
964
+ #[test]
965
+ fn new_array_is_correct() {
966
+ for byte in 0..128_u8 {
967
+ assert_eq!(AsciiChar::new(byte as char).as_byte(), byte);
968
+ }
969
+ }
970
+
971
+ #[test]
972
+ fn is_all() {
973
+ #![allow(clippy::is_digit_ascii_radix)] // testing it
974
+ for byte in 0..128_u8 {
975
+ let ch = byte as char;
976
+ let ascii = AsciiChar::new(ch);
977
+ assert_eq!(ascii.is_alphabetic(), ch.is_alphabetic());
978
+ assert_eq!(ascii.is_ascii_alphabetic(), ch.is_ascii_alphabetic());
979
+ assert_eq!(ascii.is_alphanumeric(), ch.is_alphanumeric());
980
+ assert_eq!(ascii.is_ascii_alphanumeric(), ch.is_ascii_alphanumeric());
981
+ assert_eq!(ascii.is_digit(8), ch.is_digit(8), "is_digit(8) {:?}", ch);
982
+ assert_eq!(ascii.is_digit(10), ch.is_digit(10), "is_digit(10) {:?}", ch);
983
+ assert_eq!(ascii.is_digit(16), ch.is_digit(16), "is_digit(16) {:?}", ch);
984
+ assert_eq!(ascii.is_digit(36), ch.is_digit(36), "is_digit(36) {:?}", ch);
985
+ assert_eq!(ascii.is_ascii_digit(), ch.is_ascii_digit());
986
+ assert_eq!(ascii.is_ascii_hexdigit(), ch.is_ascii_hexdigit());
987
+ assert_eq!(ascii.is_ascii_control(), ch.is_ascii_control());
988
+ assert_eq!(ascii.is_ascii_graphic(), ch.is_ascii_graphic());
989
+ assert_eq!(ascii.is_ascii_punctuation(), ch.is_ascii_punctuation());
990
+ assert_eq!(
991
+ ascii.is_whitespace(),
992
+ ch.is_whitespace(),
993
+ "{:?} ({:#04x})",
994
+ ch,
995
+ byte
996
+ );
997
+ assert_eq!(
998
+ ascii.is_ascii_whitespace(),
999
+ ch.is_ascii_whitespace(),
1000
+ "{:?} ({:#04x})",
1001
+ ch,
1002
+ byte
1003
+ );
1004
+ assert_eq!(ascii.is_uppercase(), ch.is_uppercase());
1005
+ assert_eq!(ascii.is_ascii_uppercase(), ch.is_ascii_uppercase());
1006
+ assert_eq!(ascii.is_lowercase(), ch.is_lowercase());
1007
+ assert_eq!(ascii.is_ascii_lowercase(), ch.is_ascii_lowercase());
1008
+ assert_eq!(ascii.to_ascii_uppercase(), ch.to_ascii_uppercase());
1009
+ assert_eq!(ascii.to_ascii_lowercase(), ch.to_ascii_lowercase());
1010
+ }
1011
+ }
1012
+
1013
+ #[test]
1014
+ fn is_digit_strange_radixes() {
1015
+ assert_eq!(AsciiChar::_0.is_digit(0), '0'.is_digit(0));
1016
+ assert_eq!(AsciiChar::_0.is_digit(1), '0'.is_digit(1));
1017
+ assert_eq!(AsciiChar::_5.is_digit(5), '5'.is_digit(5));
1018
+ assert_eq!(AsciiChar::z.is_digit(35), 'z'.is_digit(35));
1019
+ }
1020
+
1021
+ #[test]
1022
+ #[should_panic]
1023
+ fn is_digit_bad_radix() {
1024
+ let _ = AsciiChar::_7.is_digit(37);
1025
+ }
1026
+
1027
+ #[test]
1028
+ fn cmp_wider() {
1029
+ assert_eq!(AsciiChar::A, 'A');
1030
+ assert_eq!(b'b', AsciiChar::b);
1031
+ assert!(AsciiChar::a < 'z');
1032
+ }
1033
+
1034
+ #[test]
1035
+ fn ascii_case() {
1036
+ assert_eq!(AsciiChar::At.to_ascii_lowercase(), AsciiChar::At);
1037
+ assert_eq!(AsciiChar::At.to_ascii_uppercase(), AsciiChar::At);
1038
+ assert_eq!(AsciiChar::A.to_ascii_lowercase(), AsciiChar::a);
1039
+ assert_eq!(AsciiChar::A.to_ascii_uppercase(), AsciiChar::A);
1040
+ assert_eq!(AsciiChar::a.to_ascii_lowercase(), AsciiChar::a);
1041
+ assert_eq!(AsciiChar::a.to_ascii_uppercase(), AsciiChar::A);
1042
+
1043
+ let mut mutable = (AsciiChar::A, AsciiChar::a);
1044
+ mutable.0.make_ascii_lowercase();
1045
+ mutable.1.make_ascii_uppercase();
1046
+ assert_eq!(mutable.0, AsciiChar::a);
1047
+ assert_eq!(mutable.1, AsciiChar::A);
1048
+
1049
+ assert!(AsciiChar::LineFeed.eq_ignore_ascii_case(&AsciiChar::LineFeed));
1050
+ assert!(!AsciiChar::LineFeed.eq_ignore_ascii_case(&AsciiChar::CarriageReturn));
1051
+ assert!(AsciiChar::z.eq_ignore_ascii_case(&AsciiChar::Z));
1052
+ assert!(AsciiChar::Z.eq_ignore_ascii_case(&AsciiChar::z));
1053
+ assert!(AsciiChar::A.eq_ignore_ascii_case(&AsciiChar::a));
1054
+ assert!(!AsciiChar::K.eq_ignore_ascii_case(&AsciiChar::C));
1055
+ assert!(!AsciiChar::Z.eq_ignore_ascii_case(&AsciiChar::DEL));
1056
+ assert!(!AsciiChar::BracketOpen.eq_ignore_ascii_case(&AsciiChar::CurlyBraceOpen));
1057
+ assert!(!AsciiChar::Grave.eq_ignore_ascii_case(&AsciiChar::At));
1058
+ assert!(!AsciiChar::Grave.eq_ignore_ascii_case(&AsciiChar::DEL));
1059
+ }
1060
+
1061
+ #[test]
1062
+ #[cfg(feature = "std")]
1063
+ fn fmt_ascii() {
1064
+ assert_eq!(format!("{}", AsciiChar::t), "t");
1065
+ assert_eq!(format!("{:?}", AsciiChar::t), "'t'");
1066
+ assert_eq!(format!("{}", AsciiChar::LineFeed), "\n");
1067
+ assert_eq!(format!("{:?}", AsciiChar::LineFeed), "'\\n'");
1068
+ }
1069
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/ascii_str.rs ADDED
@@ -0,0 +1,1600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #[cfg(feature = "alloc")]
2
+ use alloc::borrow::ToOwned;
3
+ #[cfg(feature = "alloc")]
4
+ use alloc::boxed::Box;
5
+ use core::fmt;
6
+ use core::ops::{Index, IndexMut};
7
+ use core::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
8
+ use core::slice::{self, Iter, IterMut, SliceIndex};
9
+ #[cfg(feature = "std")]
10
+ use std::error::Error;
11
+ #[cfg(feature = "std")]
12
+ use std::ffi::CStr;
13
+
14
+ use ascii_char::AsciiChar;
15
+ #[cfg(feature = "alloc")]
16
+ use ascii_string::AsciiString;
17
+
18
+ /// [`AsciiStr`] represents a byte or string slice that only contains ASCII characters.
19
+ ///
20
+ /// It wraps an `[AsciiChar]` and implements many of `str`s methods and traits.
21
+ ///
22
+ /// It can be created by a checked conversion from a `str` or `[u8]`, or borrowed from an
23
+ /// `AsciiString`.
24
+ #[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
25
+ #[repr(transparent)]
26
+ pub struct AsciiStr {
27
+ slice: [AsciiChar],
28
+ }
29
+
30
+ impl AsciiStr {
31
+ /// Converts `&self` to a `&str` slice.
32
+ #[inline]
33
+ #[must_use]
34
+ pub fn as_str(&self) -> &str {
35
+ // SAFETY: All variants of `AsciiChar` are valid bytes for a `str`.
36
+ unsafe { &*(self as *const AsciiStr as *const str) }
37
+ }
38
+
39
+ /// Converts `&self` into a byte slice.
40
+ #[inline]
41
+ #[must_use]
42
+ pub fn as_bytes(&self) -> &[u8] {
43
+ // SAFETY: All variants of `AsciiChar` are valid `u8`, given they're `repr(u8)`.
44
+ unsafe { &*(self as *const AsciiStr as *const [u8]) }
45
+ }
46
+
47
+ /// Returns the entire string as slice of `AsciiChar`s.
48
+ #[inline]
49
+ #[must_use]
50
+ pub const fn as_slice(&self) -> &[AsciiChar] {
51
+ &self.slice
52
+ }
53
+
54
+ /// Returns the entire string as mutable slice of `AsciiChar`s.
55
+ #[inline]
56
+ #[must_use]
57
+ pub fn as_mut_slice(&mut self) -> &mut [AsciiChar] {
58
+ &mut self.slice
59
+ }
60
+
61
+ /// Returns a raw pointer to the `AsciiStr`'s buffer.
62
+ ///
63
+ /// The caller must ensure that the slice outlives the pointer this function returns, or else it
64
+ /// will end up pointing to garbage. Modifying the `AsciiStr` may cause it's buffer to be
65
+ /// reallocated, which would also make any pointers to it invalid.
66
+ #[inline]
67
+ #[must_use]
68
+ pub const fn as_ptr(&self) -> *const AsciiChar {
69
+ self.as_slice().as_ptr()
70
+ }
71
+
72
+ /// Returns an unsafe mutable pointer to the `AsciiStr`'s buffer.
73
+ ///
74
+ /// The caller must ensure that the slice outlives the pointer this function returns, or else it
75
+ /// will end up pointing to garbage. Modifying the `AsciiStr` may cause it's buffer to be
76
+ /// reallocated, which would also make any pointers to it invalid.
77
+ #[inline]
78
+ #[must_use]
79
+ pub fn as_mut_ptr(&mut self) -> *mut AsciiChar {
80
+ self.as_mut_slice().as_mut_ptr()
81
+ }
82
+
83
+ /// Copies the content of this `AsciiStr` into an owned `AsciiString`.
84
+ #[cfg(feature = "alloc")]
85
+ #[must_use]
86
+ pub fn to_ascii_string(&self) -> AsciiString {
87
+ AsciiString::from(self.slice.to_vec())
88
+ }
89
+
90
+ /// Converts anything that can represent a byte slice into an `AsciiStr`.
91
+ ///
92
+ /// # Errors
93
+ /// If `bytes` contains a non-ascii byte, `Err` will be returned
94
+ ///
95
+ /// # Examples
96
+ /// ```
97
+ /// # use ascii::AsciiStr;
98
+ /// let foo = AsciiStr::from_ascii(b"foo");
99
+ /// let err = AsciiStr::from_ascii("Ŋ");
100
+ /// assert_eq!(foo.unwrap().as_str(), "foo");
101
+ /// assert_eq!(err.unwrap_err().valid_up_to(), 0);
102
+ /// ```
103
+ #[inline]
104
+ pub fn from_ascii<B>(bytes: &B) -> Result<&AsciiStr, AsAsciiStrError>
105
+ where
106
+ B: AsRef<[u8]> + ?Sized,
107
+ {
108
+ bytes.as_ref().as_ascii_str()
109
+ }
110
+
111
+ /// Converts anything that can be represented as a byte slice to an `AsciiStr` without checking
112
+ /// for non-ASCII characters..
113
+ ///
114
+ /// # Safety
115
+ /// If any of the bytes in `bytes` do not represent valid ascii characters, calling
116
+ /// this function is undefined behavior.
117
+ ///
118
+ /// # Examples
119
+ /// ```
120
+ /// # use ascii::AsciiStr;
121
+ /// let foo = unsafe { AsciiStr::from_ascii_unchecked(&b"foo"[..]) };
122
+ /// assert_eq!(foo.as_str(), "foo");
123
+ /// ```
124
+ #[inline]
125
+ #[must_use]
126
+ pub unsafe fn from_ascii_unchecked(bytes: &[u8]) -> &AsciiStr {
127
+ // SAFETY: Caller guarantees all bytes in `bytes` are valid
128
+ // ascii characters.
129
+ unsafe { bytes.as_ascii_str_unchecked() }
130
+ }
131
+
132
+ /// Returns the number of characters / bytes in this ASCII sequence.
133
+ ///
134
+ /// # Examples
135
+ /// ```
136
+ /// # use ascii::AsciiStr;
137
+ /// let s = AsciiStr::from_ascii("foo").unwrap();
138
+ /// assert_eq!(s.len(), 3);
139
+ /// ```
140
+ #[inline]
141
+ #[must_use]
142
+ pub const fn len(&self) -> usize {
143
+ self.slice.len()
144
+ }
145
+
146
+ /// Returns true if the ASCII slice contains zero bytes.
147
+ ///
148
+ /// # Examples
149
+ /// ```
150
+ /// # use ascii::AsciiStr;
151
+ /// let mut empty = AsciiStr::from_ascii("").unwrap();
152
+ /// let mut full = AsciiStr::from_ascii("foo").unwrap();
153
+ /// assert!(empty.is_empty());
154
+ /// assert!(!full.is_empty());
155
+ /// ```
156
+ #[inline]
157
+ #[must_use]
158
+ pub const fn is_empty(&self) -> bool {
159
+ self.len() == 0
160
+ }
161
+
162
+ /// Returns an iterator over the characters of the `AsciiStr`.
163
+ #[inline]
164
+ #[must_use]
165
+ pub fn chars(&self) -> Chars {
166
+ Chars(self.slice.iter())
167
+ }
168
+
169
+ /// Returns an iterator over the characters of the `AsciiStr` which allows you to modify the
170
+ /// value of each `AsciiChar`.
171
+ #[inline]
172
+ #[must_use]
173
+ pub fn chars_mut(&mut self) -> CharsMut {
174
+ CharsMut(self.slice.iter_mut())
175
+ }
176
+
177
+ /// Returns an iterator over parts of the `AsciiStr` separated by a character.
178
+ ///
179
+ /// # Examples
180
+ /// ```
181
+ /// # use ascii::{AsciiStr, AsciiChar};
182
+ /// let words = AsciiStr::from_ascii("apple banana lemon").unwrap()
183
+ /// .split(AsciiChar::Space)
184
+ /// .map(|a| a.as_str())
185
+ /// .collect::<Vec<_>>();
186
+ /// assert_eq!(words, ["apple", "banana", "lemon"]);
187
+ /// ```
188
+ #[must_use]
189
+ pub fn split(&self, on: AsciiChar) -> impl DoubleEndedIterator<Item = &AsciiStr> {
190
+ Split {
191
+ on,
192
+ ended: false,
193
+ chars: self.chars(),
194
+ }
195
+ }
196
+
197
+ /// Returns an iterator over the lines of the `AsciiStr`, which are themselves `AsciiStr`s.
198
+ ///
199
+ /// Lines are ended with either `LineFeed` (`\n`), or `CarriageReturn` then `LineFeed` (`\r\n`).
200
+ ///
201
+ /// The final line ending is optional.
202
+ #[inline]
203
+ #[must_use]
204
+ pub fn lines(&self) -> impl DoubleEndedIterator<Item = &AsciiStr> {
205
+ Lines { string: self }
206
+ }
207
+
208
+ /// Returns an ASCII string slice with leading and trailing whitespace removed.
209
+ ///
210
+ /// # Examples
211
+ /// ```
212
+ /// # use ascii::AsciiStr;
213
+ /// let example = AsciiStr::from_ascii(" \twhite \tspace \t").unwrap();
214
+ /// assert_eq!("white \tspace", example.trim());
215
+ /// ```
216
+ #[must_use]
217
+ pub fn trim(&self) -> &Self {
218
+ self.trim_start().trim_end()
219
+ }
220
+
221
+ /// Returns an ASCII string slice with leading whitespace removed.
222
+ ///
223
+ /// # Examples
224
+ /// ```
225
+ /// # use ascii::AsciiStr;
226
+ /// let example = AsciiStr::from_ascii(" \twhite \tspace \t").unwrap();
227
+ /// assert_eq!("white \tspace \t", example.trim_start());
228
+ /// ```
229
+ #[must_use]
230
+ pub fn trim_start(&self) -> &Self {
231
+ let whitespace_len = self
232
+ .chars()
233
+ .position(|ch| !ch.is_whitespace())
234
+ .unwrap_or_else(|| self.len());
235
+
236
+ // SAFETY: `whitespace_len` is `0..=len`, which is at most `len`, which is a valid empty slice.
237
+ unsafe { self.as_slice().get_unchecked(whitespace_len..).into() }
238
+ }
239
+
240
+ /// Returns an ASCII string slice with trailing whitespace removed.
241
+ ///
242
+ /// # Examples
243
+ /// ```
244
+ /// # use ascii::AsciiStr;
245
+ /// let example = AsciiStr::from_ascii(" \twhite \tspace \t").unwrap();
246
+ /// assert_eq!(" \twhite \tspace", example.trim_end());
247
+ /// ```
248
+ #[must_use]
249
+ pub fn trim_end(&self) -> &Self {
250
+ // Number of whitespace characters counting from the end
251
+ let whitespace_len = self
252
+ .chars()
253
+ .rev()
254
+ .position(|ch| !ch.is_whitespace())
255
+ .unwrap_or_else(|| self.len());
256
+
257
+ // SAFETY: `whitespace_len` is `0..=len`, which is at most `len`, which is a valid empty slice, and at least `0`, which is the whole slice.
258
+ unsafe {
259
+ self.as_slice()
260
+ .get_unchecked(..self.len() - whitespace_len)
261
+ .into()
262
+ }
263
+ }
264
+
265
+ /// Compares two strings case-insensitively.
266
+ #[must_use]
267
+ pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
268
+ self.len() == other.len()
269
+ && self
270
+ .chars()
271
+ .zip(other.chars())
272
+ .all(|(ch, other_ch)| ch.eq_ignore_ascii_case(&other_ch))
273
+ }
274
+
275
+ /// Replaces lowercase letters with their uppercase equivalent.
276
+ pub fn make_ascii_uppercase(&mut self) {
277
+ for ch in self.chars_mut() {
278
+ *ch = ch.to_ascii_uppercase();
279
+ }
280
+ }
281
+
282
+ /// Replaces uppercase letters with their lowercase equivalent.
283
+ pub fn make_ascii_lowercase(&mut self) {
284
+ for ch in self.chars_mut() {
285
+ *ch = ch.to_ascii_lowercase();
286
+ }
287
+ }
288
+
289
+ /// Returns a copy of this string where letters 'a' to 'z' are mapped to 'A' to 'Z'.
290
+ #[cfg(feature = "alloc")]
291
+ #[must_use]
292
+ pub fn to_ascii_uppercase(&self) -> AsciiString {
293
+ let mut ascii_string = self.to_ascii_string();
294
+ ascii_string.make_ascii_uppercase();
295
+ ascii_string
296
+ }
297
+
298
+ /// Returns a copy of this string where letters 'A' to 'Z' are mapped to 'a' to 'z'.
299
+ #[cfg(feature = "alloc")]
300
+ #[must_use]
301
+ pub fn to_ascii_lowercase(&self) -> AsciiString {
302
+ let mut ascii_string = self.to_ascii_string();
303
+ ascii_string.make_ascii_lowercase();
304
+ ascii_string
305
+ }
306
+
307
+ /// Returns the first character if the string is not empty.
308
+ #[inline]
309
+ #[must_use]
310
+ pub fn first(&self) -> Option<AsciiChar> {
311
+ self.slice.first().copied()
312
+ }
313
+
314
+ /// Returns the last character if the string is not empty.
315
+ #[inline]
316
+ #[must_use]
317
+ pub fn last(&self) -> Option<AsciiChar> {
318
+ self.slice.last().copied()
319
+ }
320
+
321
+ /// Converts a [`Box<AsciiStr>`] into a [`AsciiString`] without copying or allocating.
322
+ #[cfg(feature = "alloc")]
323
+ #[inline]
324
+ #[must_use]
325
+ pub fn into_ascii_string(self: Box<Self>) -> AsciiString {
326
+ let slice = Box::<[AsciiChar]>::from(self);
327
+ AsciiString::from(slice.into_vec())
328
+ }
329
+ }
330
+
331
+ macro_rules! impl_partial_eq {
332
+ ($wider: ty) => {
333
+ impl PartialEq<$wider> for AsciiStr {
334
+ #[inline]
335
+ fn eq(&self, other: &$wider) -> bool {
336
+ <AsciiStr as AsRef<$wider>>::as_ref(self) == other
337
+ }
338
+ }
339
+ impl PartialEq<AsciiStr> for $wider {
340
+ #[inline]
341
+ fn eq(&self, other: &AsciiStr) -> bool {
342
+ self == <AsciiStr as AsRef<$wider>>::as_ref(other)
343
+ }
344
+ }
345
+ };
346
+ }
347
+
348
+ impl_partial_eq! {str}
349
+ impl_partial_eq! {[u8]}
350
+ impl_partial_eq! {[AsciiChar]}
351
+
352
+ #[cfg(feature = "alloc")]
353
+ impl ToOwned for AsciiStr {
354
+ type Owned = AsciiString;
355
+
356
+ #[inline]
357
+ fn to_owned(&self) -> AsciiString {
358
+ self.to_ascii_string()
359
+ }
360
+ }
361
+
362
+ impl AsRef<[u8]> for AsciiStr {
363
+ #[inline]
364
+ fn as_ref(&self) -> &[u8] {
365
+ self.as_bytes()
366
+ }
367
+ }
368
+ impl AsRef<str> for AsciiStr {
369
+ #[inline]
370
+ fn as_ref(&self) -> &str {
371
+ self.as_str()
372
+ }
373
+ }
374
+ impl AsRef<[AsciiChar]> for AsciiStr {
375
+ #[inline]
376
+ fn as_ref(&self) -> &[AsciiChar] {
377
+ &self.slice
378
+ }
379
+ }
380
+ impl AsMut<[AsciiChar]> for AsciiStr {
381
+ #[inline]
382
+ fn as_mut(&mut self) -> &mut [AsciiChar] {
383
+ &mut self.slice
384
+ }
385
+ }
386
+
387
+ impl Default for &'static AsciiStr {
388
+ #[inline]
389
+ fn default() -> &'static AsciiStr {
390
+ From::from(&[] as &[AsciiChar])
391
+ }
392
+ }
393
+ impl<'a> From<&'a [AsciiChar]> for &'a AsciiStr {
394
+ #[inline]
395
+ fn from(slice: &[AsciiChar]) -> &AsciiStr {
396
+ let ptr = slice as *const [AsciiChar] as *const AsciiStr;
397
+ unsafe { &*ptr }
398
+ }
399
+ }
400
+ impl<'a> From<&'a mut [AsciiChar]> for &'a mut AsciiStr {
401
+ #[inline]
402
+ fn from(slice: &mut [AsciiChar]) -> &mut AsciiStr {
403
+ let ptr = slice as *mut [AsciiChar] as *mut AsciiStr;
404
+ unsafe { &mut *ptr }
405
+ }
406
+ }
407
+ #[cfg(feature = "alloc")]
408
+ impl From<Box<[AsciiChar]>> for Box<AsciiStr> {
409
+ #[inline]
410
+ fn from(owned: Box<[AsciiChar]>) -> Box<AsciiStr> {
411
+ let ptr = Box::into_raw(owned) as *mut AsciiStr;
412
+ unsafe { Box::from_raw(ptr) }
413
+ }
414
+ }
415
+
416
+ impl AsRef<AsciiStr> for AsciiStr {
417
+ #[inline]
418
+ fn as_ref(&self) -> &AsciiStr {
419
+ self
420
+ }
421
+ }
422
+ impl AsMut<AsciiStr> for AsciiStr {
423
+ #[inline]
424
+ fn as_mut(&mut self) -> &mut AsciiStr {
425
+ self
426
+ }
427
+ }
428
+ impl AsRef<AsciiStr> for [AsciiChar] {
429
+ #[inline]
430
+ fn as_ref(&self) -> &AsciiStr {
431
+ self.into()
432
+ }
433
+ }
434
+ impl AsMut<AsciiStr> for [AsciiChar] {
435
+ #[inline]
436
+ fn as_mut(&mut self) -> &mut AsciiStr {
437
+ self.into()
438
+ }
439
+ }
440
+
441
+ impl<'a> From<&'a AsciiStr> for &'a [AsciiChar] {
442
+ #[inline]
443
+ fn from(astr: &AsciiStr) -> &[AsciiChar] {
444
+ &astr.slice
445
+ }
446
+ }
447
+ impl<'a> From<&'a mut AsciiStr> for &'a mut [AsciiChar] {
448
+ #[inline]
449
+ fn from(astr: &mut AsciiStr) -> &mut [AsciiChar] {
450
+ &mut astr.slice
451
+ }
452
+ }
453
+ impl<'a> From<&'a AsciiStr> for &'a [u8] {
454
+ #[inline]
455
+ fn from(astr: &AsciiStr) -> &[u8] {
456
+ astr.as_bytes()
457
+ }
458
+ }
459
+ impl<'a> From<&'a AsciiStr> for &'a str {
460
+ #[inline]
461
+ fn from(astr: &AsciiStr) -> &str {
462
+ astr.as_str()
463
+ }
464
+ }
465
+ macro_rules! widen_box {
466
+ ($wider: ty) => {
467
+ #[cfg(feature = "alloc")]
468
+ impl From<Box<AsciiStr>> for Box<$wider> {
469
+ #[inline]
470
+ fn from(owned: Box<AsciiStr>) -> Box<$wider> {
471
+ let ptr = Box::into_raw(owned) as *mut $wider;
472
+ unsafe { Box::from_raw(ptr) }
473
+ }
474
+ }
475
+ };
476
+ }
477
+ widen_box! {[AsciiChar]}
478
+ widen_box! {[u8]}
479
+ widen_box! {str}
480
+
481
+ // allows &AsciiChar to be used by generic AsciiString Extend and FromIterator
482
+ impl AsRef<AsciiStr> for AsciiChar {
483
+ fn as_ref(&self) -> &AsciiStr {
484
+ slice::from_ref(self).into()
485
+ }
486
+ }
487
+
488
+ impl fmt::Display for AsciiStr {
489
+ #[inline]
490
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
491
+ fmt::Display::fmt(self.as_str(), f)
492
+ }
493
+ }
494
+
495
+ impl fmt::Debug for AsciiStr {
496
+ #[inline]
497
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
498
+ fmt::Debug::fmt(self.as_str(), f)
499
+ }
500
+ }
501
+
502
+ macro_rules! impl_index {
503
+ ($idx:ty) => {
504
+ #[allow(clippy::indexing_slicing)] // In `Index`, if it's out of bounds, panic is the default
505
+ impl Index<$idx> for AsciiStr {
506
+ type Output = AsciiStr;
507
+
508
+ #[inline]
509
+ fn index(&self, index: $idx) -> &AsciiStr {
510
+ self.slice[index].as_ref()
511
+ }
512
+ }
513
+
514
+ #[allow(clippy::indexing_slicing)] // In `IndexMut`, if it's out of bounds, panic is the default
515
+ impl IndexMut<$idx> for AsciiStr {
516
+ #[inline]
517
+ fn index_mut(&mut self, index: $idx) -> &mut AsciiStr {
518
+ self.slice[index].as_mut()
519
+ }
520
+ }
521
+ };
522
+ }
523
+
524
+ impl_index! { Range<usize> }
525
+ impl_index! { RangeTo<usize> }
526
+ impl_index! { RangeFrom<usize> }
527
+ impl_index! { RangeFull }
528
+ impl_index! { RangeInclusive<usize> }
529
+ impl_index! { RangeToInclusive<usize> }
530
+
531
+ #[allow(clippy::indexing_slicing)] // In `Index`, if it's out of bounds, panic is the default
532
+ impl Index<usize> for AsciiStr {
533
+ type Output = AsciiChar;
534
+
535
+ #[inline]
536
+ fn index(&self, index: usize) -> &AsciiChar {
537
+ &self.slice[index]
538
+ }
539
+ }
540
+
541
+ #[allow(clippy::indexing_slicing)] // In `IndexMut`, if it's out of bounds, panic is the default
542
+ impl IndexMut<usize> for AsciiStr {
543
+ #[inline]
544
+ fn index_mut(&mut self, index: usize) -> &mut AsciiChar {
545
+ &mut self.slice[index]
546
+ }
547
+ }
548
+
549
+ /// Produces references for compatibility with `[u8]`.
550
+ ///
551
+ /// (`str` doesn't implement `IntoIterator` for its references,
552
+ /// so there is no compatibility to lose.)
553
+ impl<'a> IntoIterator for &'a AsciiStr {
554
+ type Item = &'a AsciiChar;
555
+ type IntoIter = CharsRef<'a>;
556
+ #[inline]
557
+ fn into_iter(self) -> Self::IntoIter {
558
+ CharsRef(self.as_slice().iter())
559
+ }
560
+ }
561
+
562
+ impl<'a> IntoIterator for &'a mut AsciiStr {
563
+ type Item = &'a mut AsciiChar;
564
+ type IntoIter = CharsMut<'a>;
565
+ #[inline]
566
+ fn into_iter(self) -> Self::IntoIter {
567
+ self.chars_mut()
568
+ }
569
+ }
570
+
571
+ /// A copying iterator over the characters of an `AsciiStr`.
572
+ #[derive(Clone, Debug)]
573
+ pub struct Chars<'a>(Iter<'a, AsciiChar>);
574
+ impl<'a> Chars<'a> {
575
+ /// Returns the ascii string slice with the remaining characters.
576
+ #[must_use]
577
+ pub fn as_str(&self) -> &'a AsciiStr {
578
+ self.0.as_slice().into()
579
+ }
580
+ }
581
+ impl<'a> Iterator for Chars<'a> {
582
+ type Item = AsciiChar;
583
+ #[inline]
584
+ fn next(&mut self) -> Option<AsciiChar> {
585
+ self.0.next().copied()
586
+ }
587
+ fn size_hint(&self) -> (usize, Option<usize>) {
588
+ self.0.size_hint()
589
+ }
590
+ }
591
+ impl<'a> DoubleEndedIterator for Chars<'a> {
592
+ #[inline]
593
+ fn next_back(&mut self) -> Option<AsciiChar> {
594
+ self.0.next_back().copied()
595
+ }
596
+ }
597
+ impl<'a> ExactSizeIterator for Chars<'a> {
598
+ fn len(&self) -> usize {
599
+ self.0.len()
600
+ }
601
+ }
602
+
603
+ /// A mutable iterator over the characters of an `AsciiStr`.
604
+ #[derive(Debug)]
605
+ pub struct CharsMut<'a>(IterMut<'a, AsciiChar>);
606
+ impl<'a> CharsMut<'a> {
607
+ /// Returns the ascii string slice with the remaining characters.
608
+ #[must_use]
609
+ pub fn into_str(self) -> &'a mut AsciiStr {
610
+ self.0.into_slice().into()
611
+ }
612
+ }
613
+ impl<'a> Iterator for CharsMut<'a> {
614
+ type Item = &'a mut AsciiChar;
615
+ #[inline]
616
+ fn next(&mut self) -> Option<&'a mut AsciiChar> {
617
+ self.0.next()
618
+ }
619
+ fn size_hint(&self) -> (usize, Option<usize>) {
620
+ self.0.size_hint()
621
+ }
622
+ }
623
+ impl<'a> DoubleEndedIterator for CharsMut<'a> {
624
+ #[inline]
625
+ fn next_back(&mut self) -> Option<&'a mut AsciiChar> {
626
+ self.0.next_back()
627
+ }
628
+ }
629
+ impl<'a> ExactSizeIterator for CharsMut<'a> {
630
+ fn len(&self) -> usize {
631
+ self.0.len()
632
+ }
633
+ }
634
+
635
+ /// An immutable iterator over the characters of an `AsciiStr`.
636
+ #[derive(Clone, Debug)]
637
+ pub struct CharsRef<'a>(Iter<'a, AsciiChar>);
638
+ impl<'a> CharsRef<'a> {
639
+ /// Returns the ascii string slice with the remaining characters.
640
+ #[must_use]
641
+ pub fn as_str(&self) -> &'a AsciiStr {
642
+ self.0.as_slice().into()
643
+ }
644
+ }
645
+ impl<'a> Iterator for CharsRef<'a> {
646
+ type Item = &'a AsciiChar;
647
+ #[inline]
648
+ fn next(&mut self) -> Option<&'a AsciiChar> {
649
+ self.0.next()
650
+ }
651
+ fn size_hint(&self) -> (usize, Option<usize>) {
652
+ self.0.size_hint()
653
+ }
654
+ }
655
+ impl<'a> DoubleEndedIterator for CharsRef<'a> {
656
+ #[inline]
657
+ fn next_back(&mut self) -> Option<&'a AsciiChar> {
658
+ self.0.next_back()
659
+ }
660
+ }
661
+
662
+ /// An iterator over parts of an `AsciiStr` separated by an `AsciiChar`.
663
+ ///
664
+ /// This type is created by [`AsciiChar::split()`](struct.AsciiChar.html#method.split).
665
+ #[derive(Clone, Debug)]
666
+ struct Split<'a> {
667
+ on: AsciiChar,
668
+ ended: bool,
669
+ chars: Chars<'a>,
670
+ }
671
+ impl<'a> Iterator for Split<'a> {
672
+ type Item = &'a AsciiStr;
673
+
674
+ fn next(&mut self) -> Option<&'a AsciiStr> {
675
+ if !self.ended {
676
+ let start: &AsciiStr = self.chars.as_str();
677
+ let split_on = self.on;
678
+
679
+ if let Some(at) = self.chars.position(|ch| ch == split_on) {
680
+ // SAFETY: `at` is guaranteed to be in bounds, as `position` returns `Ok(0..len)`.
681
+ Some(unsafe { start.as_slice().get_unchecked(..at).into() })
682
+ } else {
683
+ self.ended = true;
684
+ Some(start)
685
+ }
686
+ } else {
687
+ None
688
+ }
689
+ }
690
+ }
691
+ impl<'a> DoubleEndedIterator for Split<'a> {
692
+ fn next_back(&mut self) -> Option<&'a AsciiStr> {
693
+ if !self.ended {
694
+ let start: &AsciiStr = self.chars.as_str();
695
+ let split_on = self.on;
696
+
697
+ if let Some(at) = self.chars.rposition(|ch| ch == split_on) {
698
+ // SAFETY: `at` is guaranteed to be in bounds, as `rposition` returns `Ok(0..len)`, and slices `1..`, `2..`, etc... until `len..` inclusive, are valid.
699
+ Some(unsafe { start.as_slice().get_unchecked(at + 1..).into() })
700
+ } else {
701
+ self.ended = true;
702
+ Some(start)
703
+ }
704
+ } else {
705
+ None
706
+ }
707
+ }
708
+ }
709
+
710
+ /// An iterator over the lines of the internal character array.
711
+ #[derive(Clone, Debug)]
712
+ struct Lines<'a> {
713
+ string: &'a AsciiStr,
714
+ }
715
+ impl<'a> Iterator for Lines<'a> {
716
+ type Item = &'a AsciiStr;
717
+
718
+ fn next(&mut self) -> Option<&'a AsciiStr> {
719
+ if let Some(idx) = self
720
+ .string
721
+ .chars()
722
+ .position(|chr| chr == AsciiChar::LineFeed)
723
+ {
724
+ // SAFETY: `idx` is guaranteed to be `1..len`, as we get it from `position` as `0..len` and make sure it's not `0`.
725
+ let line = if idx > 0
726
+ && *unsafe { self.string.as_slice().get_unchecked(idx - 1) }
727
+ == AsciiChar::CarriageReturn
728
+ {
729
+ // SAFETY: As per above, `idx` is guaranteed to be `1..len`
730
+ unsafe { self.string.as_slice().get_unchecked(..idx - 1).into() }
731
+ } else {
732
+ // SAFETY: As per above, `idx` is guaranteed to be `0..len`
733
+ unsafe { self.string.as_slice().get_unchecked(..idx).into() }
734
+ };
735
+ // SAFETY: As per above, `idx` is guaranteed to be `0..len`, so at the extreme, slicing `len..` is a valid empty slice.
736
+ self.string = unsafe { self.string.as_slice().get_unchecked(idx + 1..).into() };
737
+ Some(line)
738
+ } else if self.string.is_empty() {
739
+ None
740
+ } else {
741
+ let line = self.string;
742
+ // SAFETY: An empty string is a valid string.
743
+ self.string = unsafe { AsciiStr::from_ascii_unchecked(b"") };
744
+ Some(line)
745
+ }
746
+ }
747
+ }
748
+
749
+ impl<'a> DoubleEndedIterator for Lines<'a> {
750
+ fn next_back(&mut self) -> Option<&'a AsciiStr> {
751
+ if self.string.is_empty() {
752
+ return None;
753
+ }
754
+
755
+ // If we end with `LF` / `CR/LF`, remove them
756
+ if let Some(AsciiChar::LineFeed) = self.string.last() {
757
+ // SAFETY: `last()` returned `Some`, so our len is at least 1.
758
+ self.string = unsafe {
759
+ self.string
760
+ .as_slice()
761
+ .get_unchecked(..self.string.len() - 1)
762
+ .into()
763
+ };
764
+
765
+ if let Some(AsciiChar::CarriageReturn) = self.string.last() {
766
+ // SAFETY: `last()` returned `Some`, so our len is at least 1.
767
+ self.string = unsafe {
768
+ self.string
769
+ .as_slice()
770
+ .get_unchecked(..self.string.len() - 1)
771
+ .into()
772
+ };
773
+ }
774
+ }
775
+
776
+ // Get the position of the first `LF` from the end.
777
+ let lf_rev_pos = self
778
+ .string
779
+ .chars()
780
+ .rev()
781
+ .position(|ch| ch == AsciiChar::LineFeed)
782
+ .unwrap_or_else(|| self.string.len());
783
+
784
+ // SAFETY: `lf_rev_pos` will be in range `0..=len`, so `len - lf_rev_pos`
785
+ // will be within `0..=len`, making it correct as a start and end
786
+ // point for the strings.
787
+ let line = unsafe {
788
+ self.string
789
+ .as_slice()
790
+ .get_unchecked(self.string.len() - lf_rev_pos..)
791
+ .into()
792
+ };
793
+ self.string = unsafe {
794
+ self.string
795
+ .as_slice()
796
+ .get_unchecked(..self.string.len() - lf_rev_pos)
797
+ .into()
798
+ };
799
+ Some(line)
800
+ }
801
+ }
802
+
803
+ /// Error that is returned when a sequence of `u8` are not all ASCII.
804
+ ///
805
+ /// Is used by `As[Mut]AsciiStr` and the `from_ascii` method on `AsciiStr` and `AsciiString`.
806
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
807
+ pub struct AsAsciiStrError(usize);
808
+
809
+ const ERRORMSG_STR: &str = "one or more bytes are not ASCII";
810
+
811
+ impl AsAsciiStrError {
812
+ /// Returns the index of the first non-ASCII byte.
813
+ ///
814
+ /// It is the maximum index such that `from_ascii(input[..index])` would return `Ok(_)`.
815
+ #[inline]
816
+ #[must_use]
817
+ pub const fn valid_up_to(self) -> usize {
818
+ self.0
819
+ }
820
+ #[cfg(not(feature = "std"))]
821
+ /// Returns a description for this error, like `std::error::Error::description`.
822
+ #[inline]
823
+ #[must_use]
824
+ #[allow(clippy::unused_self)]
825
+ pub const fn description(&self) -> &'static str {
826
+ ERRORMSG_STR
827
+ }
828
+ }
829
+ impl fmt::Display for AsAsciiStrError {
830
+ fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
831
+ write!(fmtr, "the byte at index {} is not ASCII", self.0)
832
+ }
833
+ }
834
+ #[cfg(feature = "std")]
835
+ impl Error for AsAsciiStrError {
836
+ #[inline]
837
+ fn description(&self) -> &'static str {
838
+ ERRORMSG_STR
839
+ }
840
+ }
841
+
842
+ /// Convert slices of bytes or [`AsciiChar`] to [`AsciiStr`].
843
+ // Could nearly replace this trait with SliceIndex, but its methods isn't even
844
+ // on a path for stabilization.
845
+ pub trait AsAsciiStr {
846
+ /// Used to constrain `SliceIndex`
847
+ #[doc(hidden)]
848
+ type Inner;
849
+ /// Convert a subslice to an ASCII slice.
850
+ ///
851
+ /// # Errors
852
+ /// Returns `Err` if the range is out of bounds or if not all bytes in the
853
+ /// slice are ASCII. The value in the error will be the index of the first
854
+ /// non-ASCII byte or the end of the slice.
855
+ ///
856
+ /// # Examples
857
+ /// ```
858
+ /// use ascii::AsAsciiStr;
859
+ /// assert!("'zoä'".slice_ascii(..3).is_ok());
860
+ /// assert!("'zoä'".slice_ascii(0..4).is_err());
861
+ /// assert!("'zoä'".slice_ascii(5..=5).is_ok());
862
+ /// assert!("'zoä'".slice_ascii(4..).is_err());
863
+ /// assert!(b"\r\n".slice_ascii(..).is_ok());
864
+ /// ```
865
+ fn slice_ascii<R>(&self, range: R) -> Result<&AsciiStr, AsAsciiStrError>
866
+ where
867
+ R: SliceIndex<[Self::Inner], Output = [Self::Inner]>;
868
+ /// Convert to an ASCII slice.
869
+ ///
870
+ /// # Errors
871
+ /// Returns `Err` if not all bytes are valid ascii values.
872
+ ///
873
+ /// # Example
874
+ /// ```
875
+ /// use ascii::{AsAsciiStr, AsciiChar};
876
+ /// assert!("ASCII".as_ascii_str().is_ok());
877
+ /// assert!(b"\r\n".as_ascii_str().is_ok());
878
+ /// assert!("'zoä'".as_ascii_str().is_err());
879
+ /// assert!(b"\xff".as_ascii_str().is_err());
880
+ /// assert!([AsciiChar::C][..].as_ascii_str().is_ok()); // infallible
881
+ /// ```
882
+ fn as_ascii_str(&self) -> Result<&AsciiStr, AsAsciiStrError> {
883
+ self.slice_ascii(..)
884
+ }
885
+ /// Get a single ASCII character from the slice.
886
+ ///
887
+ /// Returns `None` if the index is out of bounds or the byte is not ASCII.
888
+ ///
889
+ /// # Examples
890
+ /// ```
891
+ /// use ascii::{AsAsciiStr, AsciiChar};
892
+ /// assert_eq!("'zoä'".get_ascii(4), None);
893
+ /// assert_eq!("'zoä'".get_ascii(5), Some(AsciiChar::Apostrophe));
894
+ /// assert_eq!("'zoä'".get_ascii(6), None);
895
+ /// ```
896
+ fn get_ascii(&self, index: usize) -> Option<AsciiChar> {
897
+ self.slice_ascii(index..=index)
898
+ .ok()
899
+ .and_then(AsciiStr::first)
900
+ }
901
+ /// Convert to an ASCII slice without checking for non-ASCII characters.
902
+ ///
903
+ /// # Safety
904
+ /// Calling this function when `self` contains non-ascii characters is
905
+ /// undefined behavior.
906
+ ///
907
+ /// # Examples
908
+ ///
909
+ unsafe fn as_ascii_str_unchecked(&self) -> &AsciiStr;
910
+ }
911
+
912
+ /// Convert mutable slices of bytes or [`AsciiChar`] to [`AsciiStr`].
913
+ pub trait AsMutAsciiStr: AsAsciiStr {
914
+ /// Convert a subslice to an ASCII slice.
915
+ ///
916
+ /// # Errors
917
+ /// This function returns `Err` if range is out of bounds, or if
918
+ /// `self` contains non-ascii values
919
+ fn slice_ascii_mut<R>(&mut self, range: R) -> Result<&mut AsciiStr, AsAsciiStrError>
920
+ where
921
+ R: SliceIndex<[Self::Inner], Output = [Self::Inner]>;
922
+
923
+ /// Convert to a mutable ASCII slice.
924
+ ///
925
+ /// # Errors
926
+ /// This function returns `Err` if `self` contains non-ascii values
927
+ fn as_mut_ascii_str(&mut self) -> Result<&mut AsciiStr, AsAsciiStrError> {
928
+ self.slice_ascii_mut(..)
929
+ }
930
+
931
+ /// Convert to a mutable ASCII slice without checking for non-ASCII characters.
932
+ ///
933
+ /// # Safety
934
+ /// Calling this function when `self` contains non-ascii characters is
935
+ /// undefined behavior.
936
+ unsafe fn as_mut_ascii_str_unchecked(&mut self) -> &mut AsciiStr;
937
+ }
938
+
939
+ // These generic implementations mirror the generic implementations for AsRef<T> in core.
940
+ impl<'a, T> AsAsciiStr for &'a T
941
+ where
942
+ T: AsAsciiStr + ?Sized,
943
+ {
944
+ type Inner = <T as AsAsciiStr>::Inner;
945
+ fn slice_ascii<R>(&self, range: R) -> Result<&AsciiStr, AsAsciiStrError>
946
+ where
947
+ R: SliceIndex<[Self::Inner], Output = [Self::Inner]>,
948
+ {
949
+ <T as AsAsciiStr>::slice_ascii(*self, range)
950
+ }
951
+
952
+ unsafe fn as_ascii_str_unchecked(&self) -> &AsciiStr {
953
+ // SAFETY: Caller guarantees `self` does not contain non-ascii characters
954
+ unsafe { <T as AsAsciiStr>::as_ascii_str_unchecked(*self) }
955
+ }
956
+ }
957
+
958
+ impl<'a, T> AsAsciiStr for &'a mut T
959
+ where
960
+ T: AsAsciiStr + ?Sized,
961
+ {
962
+ type Inner = <T as AsAsciiStr>::Inner;
963
+ fn slice_ascii<R>(&self, range: R) -> Result<&AsciiStr, AsAsciiStrError>
964
+ where
965
+ R: SliceIndex<[Self::Inner], Output = [Self::Inner]>,
966
+ {
967
+ <T as AsAsciiStr>::slice_ascii(*self, range)
968
+ }
969
+
970
+ unsafe fn as_ascii_str_unchecked(&self) -> &AsciiStr {
971
+ // SAFETY: Caller guarantees `self` does not contain non-ascii characters
972
+ unsafe { <T as AsAsciiStr>::as_ascii_str_unchecked(*self) }
973
+ }
974
+ }
975
+
976
+ impl<'a, T> AsMutAsciiStr for &'a mut T
977
+ where
978
+ T: AsMutAsciiStr + ?Sized,
979
+ {
980
+ fn slice_ascii_mut<R>(&mut self, range: R) -> Result<&mut AsciiStr, AsAsciiStrError>
981
+ where
982
+ R: SliceIndex<[Self::Inner], Output = [Self::Inner]>,
983
+ {
984
+ <T as AsMutAsciiStr>::slice_ascii_mut(*self, range)
985
+ }
986
+
987
+ unsafe fn as_mut_ascii_str_unchecked(&mut self) -> &mut AsciiStr {
988
+ // SAFETY: Caller guarantees `self` does not contain non-ascii characters
989
+ unsafe { <T as AsMutAsciiStr>::as_mut_ascii_str_unchecked(*self) }
990
+ }
991
+ }
992
+
993
+ impl AsAsciiStr for AsciiStr {
994
+ type Inner = AsciiChar;
995
+
996
+ fn slice_ascii<R>(&self, range: R) -> Result<&AsciiStr, AsAsciiStrError>
997
+ where
998
+ R: SliceIndex<[AsciiChar], Output = [AsciiChar]>,
999
+ {
1000
+ self.slice.slice_ascii(range)
1001
+ }
1002
+
1003
+ #[inline]
1004
+ fn as_ascii_str(&self) -> Result<&AsciiStr, AsAsciiStrError> {
1005
+ Ok(self)
1006
+ }
1007
+
1008
+ #[inline]
1009
+ unsafe fn as_ascii_str_unchecked(&self) -> &AsciiStr {
1010
+ self
1011
+ }
1012
+
1013
+ #[inline]
1014
+ fn get_ascii(&self, index: usize) -> Option<AsciiChar> {
1015
+ self.slice.get_ascii(index)
1016
+ }
1017
+ }
1018
+ impl AsMutAsciiStr for AsciiStr {
1019
+ fn slice_ascii_mut<R>(&mut self, range: R) -> Result<&mut AsciiStr, AsAsciiStrError>
1020
+ where
1021
+ R: SliceIndex<[AsciiChar], Output = [AsciiChar]>,
1022
+ {
1023
+ self.slice.slice_ascii_mut(range)
1024
+ }
1025
+
1026
+ #[inline]
1027
+ unsafe fn as_mut_ascii_str_unchecked(&mut self) -> &mut AsciiStr {
1028
+ self
1029
+ }
1030
+ }
1031
+
1032
+ impl AsAsciiStr for [AsciiChar] {
1033
+ type Inner = AsciiChar;
1034
+ fn slice_ascii<R>(&self, range: R) -> Result<&AsciiStr, AsAsciiStrError>
1035
+ where
1036
+ R: SliceIndex<[AsciiChar], Output = [AsciiChar]>,
1037
+ {
1038
+ match self.get(range) {
1039
+ Some(slice) => Ok(slice.into()),
1040
+ None => Err(AsAsciiStrError(self.len())),
1041
+ }
1042
+ }
1043
+
1044
+ #[inline]
1045
+ fn as_ascii_str(&self) -> Result<&AsciiStr, AsAsciiStrError> {
1046
+ Ok(self.into())
1047
+ }
1048
+
1049
+ #[inline]
1050
+ unsafe fn as_ascii_str_unchecked(&self) -> &AsciiStr {
1051
+ <&AsciiStr>::from(self)
1052
+ }
1053
+
1054
+ #[inline]
1055
+ fn get_ascii(&self, index: usize) -> Option<AsciiChar> {
1056
+ self.get(index).copied()
1057
+ }
1058
+ }
1059
+ impl AsMutAsciiStr for [AsciiChar] {
1060
+ fn slice_ascii_mut<R>(&mut self, range: R) -> Result<&mut AsciiStr, AsAsciiStrError>
1061
+ where
1062
+ R: SliceIndex<[AsciiChar], Output = [AsciiChar]>,
1063
+ {
1064
+ let len = self.len();
1065
+ match self.get_mut(range) {
1066
+ Some(slice) => Ok(slice.into()),
1067
+ None => Err(AsAsciiStrError(len)),
1068
+ }
1069
+ }
1070
+ #[inline]
1071
+ unsafe fn as_mut_ascii_str_unchecked(&mut self) -> &mut AsciiStr {
1072
+ <&mut AsciiStr>::from(self)
1073
+ }
1074
+ }
1075
+
1076
+ impl AsAsciiStr for [u8] {
1077
+ type Inner = u8;
1078
+
1079
+ fn slice_ascii<R>(&self, range: R) -> Result<&AsciiStr, AsAsciiStrError>
1080
+ where
1081
+ R: SliceIndex<[u8], Output = [u8]>,
1082
+ {
1083
+ if let Some(slice) = self.get(range) {
1084
+ slice.as_ascii_str().map_err(|AsAsciiStrError(not_ascii)| {
1085
+ let offset = slice.as_ptr() as usize - self.as_ptr() as usize;
1086
+ AsAsciiStrError(offset + not_ascii)
1087
+ })
1088
+ } else {
1089
+ Err(AsAsciiStrError(self.len()))
1090
+ }
1091
+ }
1092
+
1093
+ fn as_ascii_str(&self) -> Result<&AsciiStr, AsAsciiStrError> {
1094
+ // is_ascii is likely optimized
1095
+ if self.is_ascii() {
1096
+ // SAFETY: `is_ascii` guarantees all bytes are within ascii range.
1097
+ unsafe { Ok(self.as_ascii_str_unchecked()) }
1098
+ } else {
1099
+ Err(AsAsciiStrError(
1100
+ self.iter().take_while(|&b| b.is_ascii()).count(),
1101
+ ))
1102
+ }
1103
+ }
1104
+
1105
+ #[inline]
1106
+ unsafe fn as_ascii_str_unchecked(&self) -> &AsciiStr {
1107
+ // SAFETY: Caller guarantees `self` does not contain non-ascii characters
1108
+ unsafe { &*(self as *const [u8] as *const AsciiStr) }
1109
+ }
1110
+ }
1111
+ impl AsMutAsciiStr for [u8] {
1112
+ fn slice_ascii_mut<R>(&mut self, range: R) -> Result<&mut AsciiStr, AsAsciiStrError>
1113
+ where
1114
+ R: SliceIndex<[u8], Output = [u8]>,
1115
+ {
1116
+ let (ptr, len) = (self.as_ptr(), self.len());
1117
+ if let Some(slice) = self.get_mut(range) {
1118
+ let slice_ptr = slice.as_ptr();
1119
+ slice
1120
+ .as_mut_ascii_str()
1121
+ .map_err(|AsAsciiStrError(not_ascii)| {
1122
+ let offset = slice_ptr as usize - ptr as usize;
1123
+ AsAsciiStrError(offset + not_ascii)
1124
+ })
1125
+ } else {
1126
+ Err(AsAsciiStrError(len))
1127
+ }
1128
+ }
1129
+
1130
+ fn as_mut_ascii_str(&mut self) -> Result<&mut AsciiStr, AsAsciiStrError> {
1131
+ // is_ascii() is likely optimized
1132
+ if self.is_ascii() {
1133
+ // SAFETY: `is_ascii` guarantees all bytes are within ascii range.
1134
+ unsafe { Ok(self.as_mut_ascii_str_unchecked()) }
1135
+ } else {
1136
+ Err(AsAsciiStrError(
1137
+ self.iter().take_while(|&b| b.is_ascii()).count(),
1138
+ ))
1139
+ }
1140
+ }
1141
+
1142
+ #[inline]
1143
+ unsafe fn as_mut_ascii_str_unchecked(&mut self) -> &mut AsciiStr {
1144
+ // SAFETY: Caller guarantees `self` does not contain non-ascii characters
1145
+ unsafe { &mut *(self as *mut [u8] as *mut AsciiStr) }
1146
+ }
1147
+ }
1148
+
1149
+ impl AsAsciiStr for str {
1150
+ type Inner = u8;
1151
+ fn slice_ascii<R>(&self, range: R) -> Result<&AsciiStr, AsAsciiStrError>
1152
+ where
1153
+ R: SliceIndex<[u8], Output = [u8]>,
1154
+ {
1155
+ self.as_bytes().slice_ascii(range)
1156
+ }
1157
+ fn as_ascii_str(&self) -> Result<&AsciiStr, AsAsciiStrError> {
1158
+ self.as_bytes().as_ascii_str()
1159
+ }
1160
+ #[inline]
1161
+ unsafe fn as_ascii_str_unchecked(&self) -> &AsciiStr {
1162
+ // SAFETY: Caller guarantees `self` does not contain non-ascii characters
1163
+ unsafe { self.as_bytes().as_ascii_str_unchecked() }
1164
+ }
1165
+ }
1166
+ impl AsMutAsciiStr for str {
1167
+ fn slice_ascii_mut<R>(&mut self, range: R) -> Result<&mut AsciiStr, AsAsciiStrError>
1168
+ where
1169
+ R: SliceIndex<[u8], Output = [u8]>,
1170
+ {
1171
+ // SAFETY: We don't modify the reference in this function, and the caller may
1172
+ // only modify it to include valid ascii characters.
1173
+ let bytes = unsafe { self.as_bytes_mut() };
1174
+ match bytes.get_mut(range) {
1175
+ // Valid ascii slice
1176
+ Some(slice) if slice.is_ascii() => {
1177
+ // SAFETY: All bytes are ascii, so this cast is valid
1178
+ let ptr = slice.as_mut_ptr().cast::<AsciiChar>();
1179
+ let len = slice.len();
1180
+
1181
+ // SAFETY: The pointer is valid for `len` elements, as it came
1182
+ // from a slice.
1183
+ unsafe {
1184
+ let slice = core::slice::from_raw_parts_mut(ptr, len);
1185
+ Ok(<&mut AsciiStr>::from(slice))
1186
+ }
1187
+ }
1188
+ Some(slice) => {
1189
+ let not_ascii_len = slice.iter().copied().take_while(u8::is_ascii).count();
1190
+ let offset = slice.as_ptr() as usize - self.as_ptr() as usize;
1191
+
1192
+ Err(AsAsciiStrError(offset + not_ascii_len))
1193
+ }
1194
+ None => Err(AsAsciiStrError(self.len())),
1195
+ }
1196
+ }
1197
+ fn as_mut_ascii_str(&mut self) -> Result<&mut AsciiStr, AsAsciiStrError> {
1198
+ match self.bytes().position(|b| !b.is_ascii()) {
1199
+ Some(index) => Err(AsAsciiStrError(index)),
1200
+ // SAFETY: All bytes were iterated, and all were ascii
1201
+ None => unsafe { Ok(self.as_mut_ascii_str_unchecked()) },
1202
+ }
1203
+ }
1204
+ #[inline]
1205
+ unsafe fn as_mut_ascii_str_unchecked(&mut self) -> &mut AsciiStr {
1206
+ // SAFETY: Caller guarantees `self` does not contain non-ascii characters
1207
+ &mut *(self as *mut str as *mut AsciiStr)
1208
+ }
1209
+ }
1210
+
1211
+ /// Note that the trailing null byte will be removed in the conversion.
1212
+ #[cfg(feature = "std")]
1213
+ impl AsAsciiStr for CStr {
1214
+ type Inner = u8;
1215
+ fn slice_ascii<R>(&self, range: R) -> Result<&AsciiStr, AsAsciiStrError>
1216
+ where
1217
+ R: SliceIndex<[u8], Output = [u8]>,
1218
+ {
1219
+ self.to_bytes().slice_ascii(range)
1220
+ }
1221
+ #[inline]
1222
+ fn as_ascii_str(&self) -> Result<&AsciiStr, AsAsciiStrError> {
1223
+ self.to_bytes().as_ascii_str()
1224
+ }
1225
+ #[inline]
1226
+ unsafe fn as_ascii_str_unchecked(&self) -> &AsciiStr {
1227
+ // SAFETY: Caller guarantees `self` does not contain non-ascii characters
1228
+ unsafe { self.to_bytes().as_ascii_str_unchecked() }
1229
+ }
1230
+ }
1231
+
1232
+ #[cfg(test)]
1233
+ mod tests {
1234
+ use super::{AsAsciiStr, AsAsciiStrError, AsMutAsciiStr, AsciiStr};
1235
+ #[cfg(feature = "alloc")]
1236
+ use alloc::string::{String, ToString};
1237
+ #[cfg(feature = "alloc")]
1238
+ use alloc::vec::Vec;
1239
+ use AsciiChar;
1240
+
1241
+ /// Ensures that common types, `str`, `[u8]`, `AsciiStr` and their
1242
+ /// references, shared and mutable implement `AsAsciiStr`.
1243
+ #[test]
1244
+ fn generic_as_ascii_str() {
1245
+ // Generic function to ensure `C` implements `AsAsciiStr`
1246
+ fn generic<C: AsAsciiStr + ?Sized>(c: &C) -> Result<&AsciiStr, AsAsciiStrError> {
1247
+ c.as_ascii_str()
1248
+ }
1249
+
1250
+ let arr = [AsciiChar::A];
1251
+ let ascii_str = arr.as_ref().into();
1252
+ let mut mut_arr = arr; // Note: We need a second copy to prevent overlapping mutable borrows.
1253
+ let mut_ascii_str = mut_arr.as_mut().into();
1254
+ let mut_arr_mut_ref: &mut [AsciiChar] = &mut [AsciiChar::A];
1255
+ let mut string_bytes = [b'A'];
1256
+ let string_mut = unsafe { core::str::from_utf8_unchecked_mut(&mut string_bytes) }; // SAFETY: 'A' is a valid string.
1257
+ let string_mut_bytes: &mut [u8] = &mut [b'A'];
1258
+
1259
+ // Note: This is a trick because `rustfmt` doesn't support
1260
+ // attributes on blocks yet.
1261
+ #[rustfmt::skip]
1262
+ let _ = [
1263
+ assert_eq!(generic::<str >("A" ), Ok(ascii_str)),
1264
+ assert_eq!(generic::<[u8] >(&b"A"[..] ), Ok(ascii_str)),
1265
+ assert_eq!(generic::<AsciiStr >(ascii_str ), Ok(ascii_str)),
1266
+ assert_eq!(generic::<[AsciiChar] >(&arr ), Ok(ascii_str)),
1267
+ assert_eq!(generic::<&str >(&"A" ), Ok(ascii_str)),
1268
+ assert_eq!(generic::<&[u8] >(&&b"A"[..] ), Ok(ascii_str)),
1269
+ assert_eq!(generic::<&AsciiStr >(&ascii_str ), Ok(ascii_str)),
1270
+ assert_eq!(generic::<&[AsciiChar] >(&&arr[..] ), Ok(ascii_str)),
1271
+ assert_eq!(generic::<&mut str >(&string_mut ), Ok(ascii_str)),
1272
+ assert_eq!(generic::<&mut [u8] >(&string_mut_bytes), Ok(ascii_str)),
1273
+ assert_eq!(generic::<&mut AsciiStr >(&mut_ascii_str ), Ok(ascii_str)),
1274
+ assert_eq!(generic::<&mut [AsciiChar]>(&mut_arr_mut_ref ), Ok(ascii_str)),
1275
+ ];
1276
+ }
1277
+
1278
+ #[cfg(feature = "std")]
1279
+ #[test]
1280
+ fn cstring_as_ascii_str() {
1281
+ use std::ffi::CString;
1282
+ fn generic<C: AsAsciiStr + ?Sized>(c: &C) -> Result<&AsciiStr, AsAsciiStrError> {
1283
+ c.as_ascii_str()
1284
+ }
1285
+ let arr = [AsciiChar::A];
1286
+ let ascii_str: &AsciiStr = arr.as_ref().into();
1287
+ let cstr = CString::new("A").unwrap();
1288
+ assert_eq!(generic(&*cstr), Ok(ascii_str));
1289
+ }
1290
+
1291
+ #[test]
1292
+ fn generic_as_mut_ascii_str() {
1293
+ fn generic_mut<C: AsMutAsciiStr + ?Sized>(
1294
+ c: &mut C,
1295
+ ) -> Result<&mut AsciiStr, AsAsciiStrError> {
1296
+ c.as_mut_ascii_str()
1297
+ }
1298
+
1299
+ let mut arr_mut = [AsciiChar::B];
1300
+ let mut ascii_str_mut: &mut AsciiStr = arr_mut.as_mut().into();
1301
+ // Need a second reference to prevent overlapping mutable borrows
1302
+ let mut arr_mut_2 = [AsciiChar::B];
1303
+ let ascii_str_mut_2: &mut AsciiStr = arr_mut_2.as_mut().into();
1304
+ assert_eq!(generic_mut(&mut ascii_str_mut), Ok(&mut *ascii_str_mut_2));
1305
+ assert_eq!(generic_mut(ascii_str_mut), Ok(&mut *ascii_str_mut_2));
1306
+ }
1307
+
1308
+ #[test]
1309
+ fn as_ascii_str() {
1310
+ macro_rules! err {{$i:expr} => {Err(AsAsciiStrError($i))}}
1311
+ let s = "abčd";
1312
+ let b = s.as_bytes();
1313
+ assert_eq!(s.as_ascii_str(), err!(2));
1314
+ assert_eq!(b.as_ascii_str(), err!(2));
1315
+ let a: &AsciiStr = [AsciiChar::a, AsciiChar::b][..].as_ref();
1316
+ assert_eq!(s[..2].as_ascii_str(), Ok(a));
1317
+ assert_eq!(b[..2].as_ascii_str(), Ok(a));
1318
+ assert_eq!(s.slice_ascii(..2), Ok(a));
1319
+ assert_eq!(b.slice_ascii(..2), Ok(a));
1320
+ assert_eq!(s.slice_ascii(..=2), err!(2));
1321
+ assert_eq!(b.slice_ascii(..=2), err!(2));
1322
+ assert_eq!(s.get_ascii(4), Some(AsciiChar::d));
1323
+ assert_eq!(b.get_ascii(4), Some(AsciiChar::d));
1324
+ assert_eq!(s.get_ascii(3), None);
1325
+ assert_eq!(b.get_ascii(3), None);
1326
+ assert_eq!(s.get_ascii(b.len()), None);
1327
+ assert_eq!(b.get_ascii(b.len()), None);
1328
+ assert_eq!(a.get_ascii(0), Some(AsciiChar::a));
1329
+ assert_eq!(a.get_ascii(a.len()), None);
1330
+ }
1331
+
1332
+ #[test]
1333
+ #[cfg(feature = "std")]
1334
+ fn cstr_as_ascii_str() {
1335
+ use std::ffi::CStr;
1336
+ macro_rules! err {{$i:expr} => {Err(AsAsciiStrError($i))}}
1337
+ let cstr = CStr::from_bytes_with_nul(b"a\xbbcde\xffg\0").unwrap();
1338
+ assert_eq!(cstr.as_ascii_str(), err!(1));
1339
+ assert_eq!(cstr.slice_ascii(2..), err!(5));
1340
+ assert_eq!(cstr.get_ascii(5), None);
1341
+ assert_eq!(cstr.get_ascii(6), Some(AsciiChar::g));
1342
+ assert_eq!(cstr.get_ascii(7), None);
1343
+ let ascii_slice = &[AsciiChar::X, AsciiChar::Y, AsciiChar::Z, AsciiChar::Null][..];
1344
+ let ascii_str: &AsciiStr = ascii_slice.as_ref();
1345
+ let cstr = CStr::from_bytes_with_nul(ascii_str.as_bytes()).unwrap();
1346
+ assert_eq!(cstr.slice_ascii(..2), Ok(&ascii_str[..2]));
1347
+ assert_eq!(cstr.as_ascii_str(), Ok(&ascii_str[..3]));
1348
+ }
1349
+
1350
+ #[test]
1351
+ #[cfg(feature = "alloc")]
1352
+ fn as_mut_ascii_str() {
1353
+ macro_rules! err {{$i:expr} => {Err(AsAsciiStrError($i))}}
1354
+ let mut s: String = "abčd".to_string();
1355
+ let mut b: Vec<u8> = s.clone().into();
1356
+ let mut first = [AsciiChar::a, AsciiChar::b];
1357
+ let mut second = [AsciiChar::d];
1358
+ assert_eq!(s.as_mut_ascii_str(), err!(2));
1359
+ assert_eq!(b.as_mut_ascii_str(), err!(2));
1360
+ assert_eq!(s.slice_ascii_mut(..), err!(2));
1361
+ assert_eq!(b.slice_ascii_mut(..), err!(2));
1362
+ assert_eq!(s[..2].as_mut_ascii_str(), Ok((&mut first[..]).into()));
1363
+ assert_eq!(b[..2].as_mut_ascii_str(), Ok((&mut first[..]).into()));
1364
+ assert_eq!(s.slice_ascii_mut(0..2), Ok((&mut first[..]).into()));
1365
+ assert_eq!(b.slice_ascii_mut(0..2), Ok((&mut first[..]).into()));
1366
+ assert_eq!(s.slice_ascii_mut(4..), Ok((&mut second[..]).into()));
1367
+ assert_eq!(b.slice_ascii_mut(4..), Ok((&mut second[..]).into()));
1368
+ assert_eq!(s.slice_ascii_mut(4..=10), err!(5));
1369
+ assert_eq!(b.slice_ascii_mut(4..=10), err!(5));
1370
+ }
1371
+
1372
+ #[test]
1373
+ fn default() {
1374
+ let default: &'static AsciiStr = Default::default();
1375
+ assert!(default.is_empty());
1376
+ }
1377
+
1378
+ #[test]
1379
+ #[allow(clippy::redundant_slicing)]
1380
+ fn index() {
1381
+ let mut arr = [AsciiChar::A, AsciiChar::B, AsciiChar::C, AsciiChar::D];
1382
+ {
1383
+ let a: &AsciiStr = arr[..].into();
1384
+ assert_eq!(a[..].as_slice(), &a.as_slice()[..]);
1385
+ assert_eq!(a[..4].as_slice(), &a.as_slice()[..4]);
1386
+ assert_eq!(a[4..].as_slice(), &a.as_slice()[4..]);
1387
+ assert_eq!(a[2..3].as_slice(), &a.as_slice()[2..3]);
1388
+ assert_eq!(a[..=3].as_slice(), &a.as_slice()[..=3]);
1389
+ assert_eq!(a[1..=1].as_slice(), &a.as_slice()[1..=1]);
1390
+ }
1391
+ let mut copy = arr;
1392
+ let a_mut: &mut AsciiStr = { &mut arr[..] }.into();
1393
+ assert_eq!(a_mut[..].as_mut_slice(), &mut copy[..]);
1394
+ assert_eq!(a_mut[..2].as_mut_slice(), &mut copy[..2]);
1395
+ assert_eq!(a_mut[3..].as_mut_slice(), &mut copy[3..]);
1396
+ assert_eq!(a_mut[4..4].as_mut_slice(), &mut copy[4..4]);
1397
+ assert_eq!(a_mut[..=0].as_mut_slice(), &mut copy[..=0]);
1398
+ assert_eq!(a_mut[0..=2].as_mut_slice(), &mut copy[0..=2]);
1399
+ }
1400
+
1401
+ #[test]
1402
+ fn as_str() {
1403
+ let b = b"( ;";
1404
+ let v = AsciiStr::from_ascii(b).unwrap();
1405
+ assert_eq!(v.as_str(), "( ;");
1406
+ assert_eq!(AsRef::<str>::as_ref(v), "( ;");
1407
+ }
1408
+
1409
+ #[test]
1410
+ fn as_bytes() {
1411
+ let b = b"( ;";
1412
+ let v = AsciiStr::from_ascii(b).unwrap();
1413
+ assert_eq!(v.as_bytes(), b"( ;");
1414
+ assert_eq!(AsRef::<[u8]>::as_ref(v), b"( ;");
1415
+ }
1416
+
1417
+ #[test]
1418
+ fn make_ascii_case() {
1419
+ let mut bytes = ([b'a', b'@', b'A'], [b'A', b'@', b'a']);
1420
+ let a = bytes.0.as_mut_ascii_str().unwrap();
1421
+ let b = bytes.1.as_mut_ascii_str().unwrap();
1422
+ assert!(a.eq_ignore_ascii_case(b));
1423
+ assert!(b.eq_ignore_ascii_case(a));
1424
+ a.make_ascii_lowercase();
1425
+ b.make_ascii_uppercase();
1426
+ assert_eq!(a, "a@a");
1427
+ assert_eq!(b, "A@A");
1428
+ }
1429
+
1430
+ #[test]
1431
+ #[cfg(feature = "alloc")]
1432
+ fn to_ascii_case() {
1433
+ let bytes = ([b'a', b'@', b'A'], [b'A', b'@', b'a']);
1434
+ let a = bytes.0.as_ascii_str().unwrap();
1435
+ let b = bytes.1.as_ascii_str().unwrap();
1436
+ assert_eq!(a.to_ascii_lowercase().as_str(), "a@a");
1437
+ assert_eq!(a.to_ascii_uppercase().as_str(), "A@A");
1438
+ assert_eq!(b.to_ascii_lowercase().as_str(), "a@a");
1439
+ assert_eq!(b.to_ascii_uppercase().as_str(), "A@A");
1440
+ }
1441
+
1442
+ #[test]
1443
+ fn chars_iter() {
1444
+ let chars = &[
1445
+ b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd', b'\0',
1446
+ ];
1447
+ let ascii = AsciiStr::from_ascii(chars).unwrap();
1448
+ for (achar, byte) in ascii.chars().zip(chars.iter().copied()) {
1449
+ assert_eq!(achar, byte);
1450
+ }
1451
+ }
1452
+
1453
+ #[test]
1454
+ fn chars_iter_mut() {
1455
+ let chars = &mut [
1456
+ b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd', b'\0',
1457
+ ];
1458
+ let ascii = chars.as_mut_ascii_str().unwrap();
1459
+ *ascii.chars_mut().next().unwrap() = AsciiChar::H;
1460
+ assert_eq!(ascii[0], b'H');
1461
+ }
1462
+
1463
+ #[test]
1464
+ fn lines_iter() {
1465
+ use core::iter::Iterator;
1466
+
1467
+ let lines: [&str; 4] = ["foo", "bar", "", "baz"];
1468
+ let joined = "foo\r\nbar\n\nbaz\n";
1469
+ let ascii = AsciiStr::from_ascii(joined.as_bytes()).unwrap();
1470
+ for (asciiline, line) in ascii.lines().zip(&lines) {
1471
+ assert_eq!(asciiline, *line);
1472
+ }
1473
+ assert_eq!(ascii.lines().count(), lines.len());
1474
+
1475
+ let lines: [&str; 4] = ["foo", "bar", "", "baz"];
1476
+ let joined = "foo\r\nbar\n\nbaz";
1477
+ let ascii = AsciiStr::from_ascii(joined.as_bytes()).unwrap();
1478
+ for (asciiline, line) in ascii.lines().zip(&lines) {
1479
+ assert_eq!(asciiline, *line);
1480
+ }
1481
+ assert_eq!(ascii.lines().count(), lines.len());
1482
+
1483
+ let trailing_line_break = b"\n";
1484
+ let ascii = AsciiStr::from_ascii(&trailing_line_break).unwrap();
1485
+ let mut line_iter = ascii.lines();
1486
+ assert_eq!(line_iter.next(), Some(AsciiStr::from_ascii("").unwrap()));
1487
+ assert_eq!(line_iter.next(), None);
1488
+
1489
+ let empty_lines = b"\n\r\n\n\r\n";
1490
+ let mut iter_count = 0;
1491
+ let ascii = AsciiStr::from_ascii(&empty_lines).unwrap();
1492
+ for line in ascii.lines() {
1493
+ iter_count += 1;
1494
+ assert!(line.is_empty());
1495
+ }
1496
+ assert_eq!(4, iter_count);
1497
+ }
1498
+
1499
+ #[test]
1500
+ fn lines_iter_rev() {
1501
+ let joined = "foo\r\nbar\n\nbaz\n";
1502
+ let ascii = AsciiStr::from_ascii(joined.as_bytes()).unwrap();
1503
+ assert_eq!(ascii.lines().rev().count(), 4);
1504
+ assert_eq!(ascii.lines().rev().count(), joined.lines().rev().count());
1505
+ for (asciiline, line) in ascii.lines().rev().zip(joined.lines().rev()) {
1506
+ assert_eq!(asciiline, line);
1507
+ }
1508
+ let mut iter = ascii.lines();
1509
+ assert_eq!(iter.next(), Some("foo".as_ascii_str().unwrap()));
1510
+ assert_eq!(iter.next_back(), Some("baz".as_ascii_str().unwrap()));
1511
+ assert_eq!(iter.next_back(), Some("".as_ascii_str().unwrap()));
1512
+ assert_eq!(iter.next(), Some("bar".as_ascii_str().unwrap()));
1513
+
1514
+ let empty_lines = b"\n\r\n\n\r\n";
1515
+ let mut iter_count = 0;
1516
+ let ascii = AsciiStr::from_ascii(&empty_lines).unwrap();
1517
+ for line in ascii.lines().rev() {
1518
+ iter_count += 1;
1519
+ assert!(line.is_empty());
1520
+ }
1521
+ assert_eq!(4, iter_count);
1522
+ }
1523
+
1524
+ #[test]
1525
+ fn lines_iter_empty() {
1526
+ assert_eq!("".as_ascii_str().unwrap().lines().next(), None);
1527
+ assert_eq!("".as_ascii_str().unwrap().lines().next_back(), None);
1528
+ assert_eq!("".lines().next(), None);
1529
+ }
1530
+
1531
+ #[test]
1532
+ fn split_str() {
1533
+ fn split_equals_str(haystack: &str, needle: char) {
1534
+ let mut strs = haystack.split(needle);
1535
+ let mut asciis = haystack
1536
+ .as_ascii_str()
1537
+ .unwrap()
1538
+ .split(AsciiChar::from_ascii(needle).unwrap())
1539
+ .map(AsciiStr::as_str);
1540
+ loop {
1541
+ assert_eq!(asciis.size_hint(), strs.size_hint());
1542
+ let (a, s) = (asciis.next(), strs.next());
1543
+ assert_eq!(a, s);
1544
+ if a == None {
1545
+ break;
1546
+ }
1547
+ }
1548
+ // test fusedness if str's version is fused
1549
+ if strs.next() == None {
1550
+ assert_eq!(asciis.next(), None);
1551
+ }
1552
+ }
1553
+ split_equals_str("", '=');
1554
+ split_equals_str("1,2,3", ',');
1555
+ split_equals_str("foo;bar;baz;", ';');
1556
+ split_equals_str("|||", '|');
1557
+ split_equals_str(" a b c ", ' ');
1558
+ }
1559
+
1560
+ #[test]
1561
+ fn split_str_rev() {
1562
+ let words = " foo bar baz ";
1563
+ let ascii = words.as_ascii_str().unwrap();
1564
+ for (word, asciiword) in words
1565
+ .split(' ')
1566
+ .rev()
1567
+ .zip(ascii.split(AsciiChar::Space).rev())
1568
+ {
1569
+ assert_eq!(asciiword, word);
1570
+ }
1571
+ let mut iter = ascii.split(AsciiChar::Space);
1572
+ assert_eq!(iter.next(), Some("".as_ascii_str().unwrap()));
1573
+ assert_eq!(iter.next_back(), Some("".as_ascii_str().unwrap()));
1574
+ assert_eq!(iter.next(), Some("foo".as_ascii_str().unwrap()));
1575
+ assert_eq!(iter.next_back(), Some("baz".as_ascii_str().unwrap()));
1576
+ assert_eq!(iter.next_back(), Some("bar".as_ascii_str().unwrap()));
1577
+ assert_eq!(iter.next(), Some("".as_ascii_str().unwrap()));
1578
+ assert_eq!(iter.next_back(), None);
1579
+ }
1580
+
1581
+ #[test]
1582
+ fn split_str_empty() {
1583
+ let empty = <&AsciiStr>::default();
1584
+ let mut iter = empty.split(AsciiChar::NAK);
1585
+ assert_eq!(iter.next(), Some(empty));
1586
+ assert_eq!(iter.next(), None);
1587
+ let mut iter = empty.split(AsciiChar::NAK);
1588
+ assert_eq!(iter.next_back(), Some(empty));
1589
+ assert_eq!(iter.next_back(), None);
1590
+ assert_eq!("".split('s').next(), Some("")); // str.split() also produces one element
1591
+ }
1592
+
1593
+ #[test]
1594
+ #[cfg(feature = "std")]
1595
+ fn fmt_ascii_str() {
1596
+ let s = "abc".as_ascii_str().unwrap();
1597
+ assert_eq!(format!("{}", s), "abc".to_string());
1598
+ assert_eq!(format!("{:?}", s), "\"abc\"".to_string());
1599
+ }
1600
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/ascii_string.rs ADDED
@@ -0,0 +1,1057 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use alloc::borrow::{Borrow, BorrowMut, Cow, ToOwned};
2
+ use alloc::fmt;
3
+ use alloc::string::String;
4
+ use alloc::vec::Vec;
5
+ use alloc::boxed::Box;
6
+ use alloc::rc::Rc;
7
+ use alloc::sync::Arc;
8
+ #[cfg(feature = "std")]
9
+ use core::any::Any;
10
+ use core::iter::FromIterator;
11
+ use core::mem;
12
+ use core::ops::{Add, AddAssign, Deref, DerefMut, Index, IndexMut};
13
+ use core::str::FromStr;
14
+ #[cfg(feature = "std")]
15
+ use std::error::Error;
16
+ #[cfg(feature = "std")]
17
+ use std::ffi::{CStr, CString};
18
+
19
+ use ascii_char::AsciiChar;
20
+ use ascii_str::{AsAsciiStr, AsAsciiStrError, AsciiStr};
21
+
22
+ /// A growable string stored as an ASCII encoded buffer.
23
+ #[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
24
+ #[repr(transparent)]
25
+ pub struct AsciiString {
26
+ vec: Vec<AsciiChar>,
27
+ }
28
+
29
+ impl AsciiString {
30
+ /// Creates a new, empty ASCII string buffer without allocating.
31
+ ///
32
+ /// # Examples
33
+ /// ```
34
+ /// # use ascii::AsciiString;
35
+ /// let mut s = AsciiString::new();
36
+ /// ```
37
+ #[inline]
38
+ #[must_use]
39
+ pub const fn new() -> Self {
40
+ AsciiString { vec: Vec::new() }
41
+ }
42
+
43
+ /// Creates a new ASCII string buffer with the given capacity.
44
+ /// The string will be able to hold exactly `capacity` bytes without reallocating.
45
+ /// If `capacity` is 0, the ASCII string will not allocate.
46
+ ///
47
+ /// # Examples
48
+ /// ```
49
+ /// # use ascii::AsciiString;
50
+ /// let mut s = AsciiString::with_capacity(10);
51
+ /// ```
52
+ #[inline]
53
+ #[must_use]
54
+ pub fn with_capacity(capacity: usize) -> Self {
55
+ AsciiString {
56
+ vec: Vec::with_capacity(capacity),
57
+ }
58
+ }
59
+
60
+ /// Creates a new `AsciiString` from a length, capacity and pointer.
61
+ ///
62
+ /// # Safety
63
+ ///
64
+ /// This is highly unsafe, due to the number of invariants that aren't checked:
65
+ ///
66
+ /// * The memory at `buf` need to have been previously allocated by the same allocator this
67
+ /// library uses, with an alignment of 1.
68
+ /// * `length` needs to be less than or equal to `capacity`.
69
+ /// * `capacity` needs to be the correct value.
70
+ /// * `buf` must have `length` valid ascii elements and contain a total of `capacity` total,
71
+ /// possibly, uninitialized, elements.
72
+ /// * Nothing else must be using the memory `buf` points to.
73
+ ///
74
+ /// Violating these may cause problems like corrupting the allocator's internal data structures.
75
+ ///
76
+ /// # Examples
77
+ ///
78
+ /// Basic usage:
79
+ ///
80
+ /// ```
81
+ /// # use ascii::AsciiString;
82
+ /// use std::mem;
83
+ ///
84
+ /// unsafe {
85
+ /// let mut s = AsciiString::from_ascii("hello").unwrap();
86
+ /// let ptr = s.as_mut_ptr();
87
+ /// let len = s.len();
88
+ /// let capacity = s.capacity();
89
+ ///
90
+ /// mem::forget(s);
91
+ ///
92
+ /// let s = AsciiString::from_raw_parts(ptr, len, capacity);
93
+ ///
94
+ /// assert_eq!(AsciiString::from_ascii("hello").unwrap(), s);
95
+ /// }
96
+ /// ```
97
+ #[inline]
98
+ #[must_use]
99
+ pub unsafe fn from_raw_parts(buf: *mut AsciiChar, length: usize, capacity: usize) -> Self {
100
+ AsciiString {
101
+ // SAFETY: Caller guarantees that `buf` was previously allocated by this library,
102
+ // that `buf` contains `length` valid ascii elements and has a total capacity
103
+ // of `capacity` elements, and that nothing else is using the momory.
104
+ vec: unsafe { Vec::from_raw_parts(buf, length, capacity) },
105
+ }
106
+ }
107
+
108
+ /// Converts a vector of bytes to an `AsciiString` without checking for non-ASCII characters.
109
+ ///
110
+ /// # Safety
111
+ /// This function is unsafe because it does not check that the bytes passed to it are valid
112
+ /// ASCII characters. If this constraint is violated, it may cause memory unsafety issues with
113
+ /// future of the `AsciiString`, as the rest of this library assumes that `AsciiString`s are
114
+ /// ASCII encoded.
115
+ #[inline]
116
+ #[must_use]
117
+ pub unsafe fn from_ascii_unchecked<B>(bytes: B) -> Self
118
+ where
119
+ B: Into<Vec<u8>>,
120
+ {
121
+ let mut bytes = bytes.into();
122
+ // SAFETY: The caller guarantees all bytes are valid ascii bytes.
123
+ let ptr = bytes.as_mut_ptr().cast::<AsciiChar>();
124
+ let length = bytes.len();
125
+ let capacity = bytes.capacity();
126
+ mem::forget(bytes);
127
+
128
+ // SAFETY: We guarantee all invariants, as we got the
129
+ // pointer, length and capacity from a `Vec`,
130
+ // and we also guarantee the pointer is valid per
131
+ // the `SAFETY` notice above.
132
+ let vec = Vec::from_raw_parts(ptr, length, capacity);
133
+
134
+ Self { vec }
135
+ }
136
+
137
+ /// Converts anything that can represent a byte buffer into an `AsciiString`.
138
+ ///
139
+ /// # Errors
140
+ /// Returns the byte buffer if not all of the bytes are ASCII characters.
141
+ ///
142
+ /// # Examples
143
+ /// ```
144
+ /// # use ascii::AsciiString;
145
+ /// let foo = AsciiString::from_ascii("foo".to_string()).unwrap();
146
+ /// let err = AsciiString::from_ascii("Ŋ".to_string()).unwrap_err();
147
+ /// assert_eq!(foo.as_str(), "foo");
148
+ /// assert_eq!(err.into_source(), "Ŋ");
149
+ /// ```
150
+ pub fn from_ascii<B>(bytes: B) -> Result<AsciiString, FromAsciiError<B>>
151
+ where
152
+ B: Into<Vec<u8>> + AsRef<[u8]>,
153
+ {
154
+ match bytes.as_ref().as_ascii_str() {
155
+ // SAFETY: `as_ascii_str` guarantees all bytes are valid ascii bytes.
156
+ Ok(_) => Ok(unsafe { AsciiString::from_ascii_unchecked(bytes) }),
157
+ Err(e) => Err(FromAsciiError {
158
+ error: e,
159
+ owner: bytes,
160
+ }),
161
+ }
162
+ }
163
+
164
+ /// Pushes the given ASCII string onto this ASCII string buffer.
165
+ ///
166
+ /// # Examples
167
+ /// ```
168
+ /// # use ascii::{AsciiString, AsAsciiStr};
169
+ /// use std::str::FromStr;
170
+ /// let mut s = AsciiString::from_str("foo").unwrap();
171
+ /// s.push_str("bar".as_ascii_str().unwrap());
172
+ /// assert_eq!(s, "foobar".as_ascii_str().unwrap());
173
+ /// ```
174
+ #[inline]
175
+ pub fn push_str(&mut self, string: &AsciiStr) {
176
+ self.vec.extend(string.chars());
177
+ }
178
+
179
+ /// Inserts the given ASCII string at the given place in this ASCII string buffer.
180
+ ///
181
+ /// # Panics
182
+ ///
183
+ /// Panics if `idx` is larger than the `AsciiString`'s length.
184
+ ///
185
+ /// # Examples
186
+ /// ```
187
+ /// # use ascii::{AsciiString, AsAsciiStr};
188
+ /// use std::str::FromStr;
189
+ /// let mut s = AsciiString::from_str("abc").unwrap();
190
+ /// s.insert_str(1, "def".as_ascii_str().unwrap());
191
+ /// assert_eq!(&*s, "adefbc");
192
+ #[inline]
193
+ pub fn insert_str(&mut self, idx: usize, string: &AsciiStr) {
194
+ self.vec.reserve(string.len());
195
+ self.vec.splice(idx..idx, string.into_iter().copied());
196
+ }
197
+
198
+ /// Returns the number of bytes that this ASCII string buffer can hold without reallocating.
199
+ ///
200
+ /// # Examples
201
+ /// ```
202
+ /// # use ascii::AsciiString;
203
+ /// let s = String::with_capacity(10);
204
+ /// assert!(s.capacity() >= 10);
205
+ /// ```
206
+ #[inline]
207
+ #[must_use]
208
+ pub fn capacity(&self) -> usize {
209
+ self.vec.capacity()
210
+ }
211
+
212
+ /// Reserves capacity for at least `additional` more bytes to be inserted in the given
213
+ /// `AsciiString`. The collection may reserve more space to avoid frequent reallocations.
214
+ ///
215
+ /// # Panics
216
+ /// Panics if the new capacity overflows `usize`.
217
+ ///
218
+ /// # Examples
219
+ /// ```
220
+ /// # use ascii::AsciiString;
221
+ /// let mut s = AsciiString::new();
222
+ /// s.reserve(10);
223
+ /// assert!(s.capacity() >= 10);
224
+ /// ```
225
+ #[inline]
226
+ pub fn reserve(&mut self, additional: usize) {
227
+ self.vec.reserve(additional);
228
+ }
229
+
230
+ /// Reserves the minimum capacity for exactly `additional` more bytes to be inserted in the
231
+ /// given `AsciiString`. Does nothing if the capacity is already sufficient.
232
+ ///
233
+ /// Note that the allocator may give the collection more space than it requests. Therefore
234
+ /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
235
+ /// insertions are expected.
236
+ ///
237
+ /// # Panics
238
+ /// Panics if the new capacity overflows `usize`.
239
+ ///
240
+ /// # Examples
241
+ /// ```
242
+ /// # use ascii::AsciiString;
243
+ /// let mut s = AsciiString::new();
244
+ /// s.reserve_exact(10);
245
+ /// assert!(s.capacity() >= 10);
246
+ /// ```
247
+ #[inline]
248
+
249
+ pub fn reserve_exact(&mut self, additional: usize) {
250
+ self.vec.reserve_exact(additional);
251
+ }
252
+
253
+ /// Shrinks the capacity of this ASCII string buffer to match it's length.
254
+ ///
255
+ /// # Examples
256
+ /// ```
257
+ /// # use ascii::AsciiString;
258
+ /// use std::str::FromStr;
259
+ /// let mut s = AsciiString::from_str("foo").unwrap();
260
+ /// s.reserve(100);
261
+ /// assert!(s.capacity() >= 100);
262
+ /// s.shrink_to_fit();
263
+ /// assert_eq!(s.capacity(), 3);
264
+ /// ```
265
+ #[inline]
266
+
267
+ pub fn shrink_to_fit(&mut self) {
268
+ self.vec.shrink_to_fit();
269
+ }
270
+
271
+ /// Adds the given ASCII character to the end of the ASCII string.
272
+ ///
273
+ /// # Examples
274
+ /// ```
275
+ /// # use ascii::{ AsciiChar, AsciiString};
276
+ /// let mut s = AsciiString::from_ascii("abc").unwrap();
277
+ /// s.push(AsciiChar::from_ascii('1').unwrap());
278
+ /// s.push(AsciiChar::from_ascii('2').unwrap());
279
+ /// s.push(AsciiChar::from_ascii('3').unwrap());
280
+ /// assert_eq!(s, "abc123");
281
+ /// ```
282
+ #[inline]
283
+
284
+ pub fn push(&mut self, ch: AsciiChar) {
285
+ self.vec.push(ch);
286
+ }
287
+
288
+ /// Shortens a ASCII string to the specified length.
289
+ ///
290
+ /// # Panics
291
+ /// Panics if `new_len` > current length.
292
+ ///
293
+ /// # Examples
294
+ /// ```
295
+ /// # use ascii::AsciiString;
296
+ /// let mut s = AsciiString::from_ascii("hello").unwrap();
297
+ /// s.truncate(2);
298
+ /// assert_eq!(s, "he");
299
+ /// ```
300
+ #[inline]
301
+
302
+ pub fn truncate(&mut self, new_len: usize) {
303
+ self.vec.truncate(new_len);
304
+ }
305
+
306
+ /// Removes the last character from the ASCII string buffer and returns it.
307
+ /// Returns `None` if this string buffer is empty.
308
+ ///
309
+ /// # Examples
310
+ /// ```
311
+ /// # use ascii::AsciiString;
312
+ /// let mut s = AsciiString::from_ascii("foo").unwrap();
313
+ /// assert_eq!(s.pop().map(|c| c.as_char()), Some('o'));
314
+ /// assert_eq!(s.pop().map(|c| c.as_char()), Some('o'));
315
+ /// assert_eq!(s.pop().map(|c| c.as_char()), Some('f'));
316
+ /// assert_eq!(s.pop(), None);
317
+ /// ```
318
+ #[inline]
319
+ #[must_use]
320
+ pub fn pop(&mut self) -> Option<AsciiChar> {
321
+ self.vec.pop()
322
+ }
323
+
324
+ /// Removes the ASCII character at position `idx` from the buffer and returns it.
325
+ ///
326
+ /// # Warning
327
+ /// This is an O(n) operation as it requires copying every element in the buffer.
328
+ ///
329
+ /// # Panics
330
+ /// If `idx` is out of bounds this function will panic.
331
+ ///
332
+ /// # Examples
333
+ /// ```
334
+ /// # use ascii::AsciiString;
335
+ /// let mut s = AsciiString::from_ascii("foo").unwrap();
336
+ /// assert_eq!(s.remove(0).as_char(), 'f');
337
+ /// assert_eq!(s.remove(1).as_char(), 'o');
338
+ /// assert_eq!(s.remove(0).as_char(), 'o');
339
+ /// ```
340
+ #[inline]
341
+ #[must_use]
342
+ pub fn remove(&mut self, idx: usize) -> AsciiChar {
343
+ self.vec.remove(idx)
344
+ }
345
+
346
+ /// Inserts an ASCII character into the buffer at position `idx`.
347
+ ///
348
+ /// # Warning
349
+ /// This is an O(n) operation as it requires copying every element in the buffer.
350
+ ///
351
+ /// # Panics
352
+ /// If `idx` is out of bounds this function will panic.
353
+ ///
354
+ /// # Examples
355
+ /// ```
356
+ /// # use ascii::{AsciiString,AsciiChar};
357
+ /// let mut s = AsciiString::from_ascii("foo").unwrap();
358
+ /// s.insert(2, AsciiChar::b);
359
+ /// assert_eq!(s, "fobo");
360
+ /// ```
361
+ #[inline]
362
+
363
+ pub fn insert(&mut self, idx: usize, ch: AsciiChar) {
364
+ self.vec.insert(idx, ch);
365
+ }
366
+
367
+ /// Returns the number of bytes in this ASCII string.
368
+ ///
369
+ /// # Examples
370
+ /// ```
371
+ /// # use ascii::AsciiString;
372
+ /// let s = AsciiString::from_ascii("foo").unwrap();
373
+ /// assert_eq!(s.len(), 3);
374
+ /// ```
375
+ #[inline]
376
+ #[must_use]
377
+ pub fn len(&self) -> usize {
378
+ self.vec.len()
379
+ }
380
+
381
+ /// Returns true if the ASCII string contains zero bytes.
382
+ ///
383
+ /// # Examples
384
+ /// ```
385
+ /// # use ascii::{AsciiChar, AsciiString};
386
+ /// let mut s = AsciiString::new();
387
+ /// assert!(s.is_empty());
388
+ /// s.push(AsciiChar::from_ascii('a').unwrap());
389
+ /// assert!(!s.is_empty());
390
+ /// ```
391
+ #[inline]
392
+ #[must_use]
393
+ pub fn is_empty(&self) -> bool {
394
+ self.len() == 0
395
+ }
396
+
397
+ /// Truncates the ASCII string, setting length (but not capacity) to zero.
398
+ ///
399
+ /// # Examples
400
+ /// ```
401
+ /// # use ascii::AsciiString;
402
+ /// let mut s = AsciiString::from_ascii("foo").unwrap();
403
+ /// s.clear();
404
+ /// assert!(s.is_empty());
405
+ /// ```
406
+ #[inline]
407
+
408
+ pub fn clear(&mut self) {
409
+ self.vec.clear();
410
+ }
411
+
412
+ /// Converts this [`AsciiString`] into a [`Box`]`<`[`AsciiStr`]`>`.
413
+ ///
414
+ /// This will drop any excess capacity
415
+ #[inline]
416
+ #[must_use]
417
+ pub fn into_boxed_ascii_str(self) -> Box<AsciiStr> {
418
+ let slice = self.vec.into_boxed_slice();
419
+ Box::from(slice)
420
+ }
421
+ }
422
+
423
+ impl Deref for AsciiString {
424
+ type Target = AsciiStr;
425
+
426
+ #[inline]
427
+ fn deref(&self) -> &AsciiStr {
428
+ self.vec.as_slice().as_ref()
429
+ }
430
+ }
431
+
432
+ impl DerefMut for AsciiString {
433
+ #[inline]
434
+ fn deref_mut(&mut self) -> &mut AsciiStr {
435
+ self.vec.as_mut_slice().as_mut()
436
+ }
437
+ }
438
+
439
+ impl PartialEq<str> for AsciiString {
440
+ #[inline]
441
+ fn eq(&self, other: &str) -> bool {
442
+ **self == *other
443
+ }
444
+ }
445
+
446
+ impl PartialEq<AsciiString> for str {
447
+ #[inline]
448
+ fn eq(&self, other: &AsciiString) -> bool {
449
+ **other == *self
450
+ }
451
+ }
452
+
453
+ macro_rules! impl_eq {
454
+ ($lhs:ty, $rhs:ty) => {
455
+ impl PartialEq<$rhs> for $lhs {
456
+ #[inline]
457
+ fn eq(&self, other: &$rhs) -> bool {
458
+ PartialEq::eq(&**self, &**other)
459
+ }
460
+ }
461
+ };
462
+ }
463
+
464
+ impl_eq! { AsciiString, String }
465
+ impl_eq! { String, AsciiString }
466
+ impl_eq! { &AsciiStr, String }
467
+ impl_eq! { String, &AsciiStr }
468
+ impl_eq! { &AsciiStr, AsciiString }
469
+ impl_eq! { AsciiString, &AsciiStr }
470
+ impl_eq! { &str, AsciiString }
471
+ impl_eq! { AsciiString, &str }
472
+
473
+ impl Borrow<AsciiStr> for AsciiString {
474
+ #[inline]
475
+ fn borrow(&self) -> &AsciiStr {
476
+ &**self
477
+ }
478
+ }
479
+
480
+ impl BorrowMut<AsciiStr> for AsciiString {
481
+ #[inline]
482
+ fn borrow_mut(&mut self) -> &mut AsciiStr {
483
+ &mut **self
484
+ }
485
+ }
486
+
487
+ impl From<Vec<AsciiChar>> for AsciiString {
488
+ #[inline]
489
+ fn from(vec: Vec<AsciiChar>) -> Self {
490
+ AsciiString { vec }
491
+ }
492
+ }
493
+
494
+ impl From<AsciiChar> for AsciiString {
495
+ #[inline]
496
+ fn from(ch: AsciiChar) -> Self {
497
+ AsciiString { vec: vec![ch] }
498
+ }
499
+ }
500
+
501
+ impl From<AsciiString> for Vec<u8> {
502
+ fn from(mut s: AsciiString) -> Vec<u8> {
503
+ // SAFETY: All ascii bytes are valid `u8`, as we are `repr(u8)`.
504
+ // Note: We forget `self` to avoid `self.vec` from being deallocated.
505
+ let ptr = s.vec.as_mut_ptr().cast::<u8>();
506
+ let length = s.vec.len();
507
+ let capacity = s.vec.capacity();
508
+ mem::forget(s);
509
+
510
+ // SAFETY: We guarantee all invariants due to getting `ptr`, `length`
511
+ // and `capacity` from a `Vec`. We also guarantee `ptr` is valid
512
+ // due to the `SAFETY` block above.
513
+ unsafe { Vec::from_raw_parts(ptr, length, capacity) }
514
+ }
515
+ }
516
+
517
+ impl From<AsciiString> for Vec<AsciiChar> {
518
+ fn from(s: AsciiString) -> Vec<AsciiChar> {
519
+ s.vec
520
+ }
521
+ }
522
+
523
+ impl<'a> From<&'a AsciiStr> for AsciiString {
524
+ #[inline]
525
+ fn from(s: &'a AsciiStr) -> Self {
526
+ s.to_ascii_string()
527
+ }
528
+ }
529
+
530
+ impl<'a> From<&'a [AsciiChar]> for AsciiString {
531
+ #[inline]
532
+ fn from(s: &'a [AsciiChar]) -> AsciiString {
533
+ s.iter().copied().collect()
534
+ }
535
+ }
536
+
537
+ impl From<AsciiString> for String {
538
+ #[inline]
539
+ fn from(s: AsciiString) -> String {
540
+ // SAFETY: All ascii bytes are `utf8`.
541
+ unsafe { String::from_utf8_unchecked(s.into()) }
542
+ }
543
+ }
544
+
545
+ impl From<Box<AsciiStr>> for AsciiString {
546
+ #[inline]
547
+ fn from(boxed: Box<AsciiStr>) -> Self {
548
+ boxed.into_ascii_string()
549
+ }
550
+ }
551
+
552
+ impl From<AsciiString> for Box<AsciiStr> {
553
+ #[inline]
554
+ fn from(string: AsciiString) -> Self {
555
+ string.into_boxed_ascii_str()
556
+ }
557
+ }
558
+
559
+ impl From<AsciiString> for Rc<AsciiStr> {
560
+ fn from(s: AsciiString) -> Rc<AsciiStr> {
561
+ let var: Rc<[AsciiChar]> = s.vec.into();
562
+ // SAFETY: AsciiStr is repr(transparent) and thus has the same layout as [AsciiChar]
563
+ unsafe { Rc::from_raw(Rc::into_raw(var) as *const AsciiStr) }
564
+ }
565
+ }
566
+
567
+ impl From<AsciiString> for Arc<AsciiStr> {
568
+ fn from(s: AsciiString) -> Arc<AsciiStr> {
569
+ let var: Arc<[AsciiChar]> = s.vec.into();
570
+ // SAFETY: AsciiStr is repr(transparent) and thus has the same layout as [AsciiChar]
571
+ unsafe { Arc::from_raw(Arc::into_raw(var) as *const AsciiStr) }
572
+ }
573
+ }
574
+
575
+ impl<'a> From<Cow<'a, AsciiStr>> for AsciiString {
576
+ fn from(cow: Cow<'a, AsciiStr>) -> AsciiString {
577
+ cow.into_owned()
578
+ }
579
+ }
580
+
581
+ impl From<AsciiString> for Cow<'static, AsciiStr> {
582
+ fn from(string: AsciiString) -> Cow<'static, AsciiStr> {
583
+ Cow::Owned(string)
584
+ }
585
+ }
586
+
587
+ impl<'a> From<&'a AsciiStr> for Cow<'a, AsciiStr> {
588
+ fn from(s: &'a AsciiStr) -> Cow<'a, AsciiStr> {
589
+ Cow::Borrowed(s)
590
+ }
591
+ }
592
+
593
+ impl AsRef<AsciiStr> for AsciiString {
594
+ #[inline]
595
+ fn as_ref(&self) -> &AsciiStr {
596
+ &**self
597
+ }
598
+ }
599
+
600
+ impl AsRef<[AsciiChar]> for AsciiString {
601
+ #[inline]
602
+ fn as_ref(&self) -> &[AsciiChar] {
603
+ &self.vec
604
+ }
605
+ }
606
+
607
+ impl AsRef<[u8]> for AsciiString {
608
+ #[inline]
609
+ fn as_ref(&self) -> &[u8] {
610
+ self.as_bytes()
611
+ }
612
+ }
613
+
614
+ impl AsRef<str> for AsciiString {
615
+ #[inline]
616
+ fn as_ref(&self) -> &str {
617
+ self.as_str()
618
+ }
619
+ }
620
+
621
+ impl AsMut<AsciiStr> for AsciiString {
622
+ #[inline]
623
+ fn as_mut(&mut self) -> &mut AsciiStr {
624
+ &mut *self
625
+ }
626
+ }
627
+
628
+ impl AsMut<[AsciiChar]> for AsciiString {
629
+ #[inline]
630
+ fn as_mut(&mut self) -> &mut [AsciiChar] {
631
+ &mut self.vec
632
+ }
633
+ }
634
+
635
+ impl FromStr for AsciiString {
636
+ type Err = AsAsciiStrError;
637
+
638
+ fn from_str(s: &str) -> Result<AsciiString, AsAsciiStrError> {
639
+ s.as_ascii_str().map(AsciiStr::to_ascii_string)
640
+ }
641
+ }
642
+
643
+ impl fmt::Display for AsciiString {
644
+ #[inline]
645
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646
+ fmt::Display::fmt(&**self, f)
647
+ }
648
+ }
649
+
650
+ impl fmt::Debug for AsciiString {
651
+ #[inline]
652
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
653
+ fmt::Debug::fmt(&**self, f)
654
+ }
655
+ }
656
+
657
+ /// Please note that the `std::fmt::Result` returned by these methods does not support
658
+ /// transmission of an error other than that an error occurred.
659
+ impl fmt::Write for AsciiString {
660
+ fn write_str(&mut self, s: &str) -> fmt::Result {
661
+ if let Ok(astr) = AsciiStr::from_ascii(s) {
662
+ self.push_str(astr);
663
+ Ok(())
664
+ } else {
665
+ Err(fmt::Error)
666
+ }
667
+ }
668
+
669
+ fn write_char(&mut self, c: char) -> fmt::Result {
670
+ if let Ok(achar) = AsciiChar::from_ascii(c) {
671
+ self.push(achar);
672
+ Ok(())
673
+ } else {
674
+ Err(fmt::Error)
675
+ }
676
+ }
677
+ }
678
+
679
+ impl<A: AsRef<AsciiStr>> FromIterator<A> for AsciiString {
680
+ fn from_iter<I: IntoIterator<Item = A>>(iter: I) -> AsciiString {
681
+ let mut buf = AsciiString::new();
682
+ buf.extend(iter);
683
+ buf
684
+ }
685
+ }
686
+
687
+ impl<A: AsRef<AsciiStr>> Extend<A> for AsciiString {
688
+ fn extend<I: IntoIterator<Item = A>>(&mut self, iterable: I) {
689
+ let iterator = iterable.into_iter();
690
+ let (lower_bound, _) = iterator.size_hint();
691
+ self.reserve(lower_bound);
692
+ for item in iterator {
693
+ self.push_str(item.as_ref());
694
+ }
695
+ }
696
+ }
697
+
698
+ impl<'a> Add<&'a AsciiStr> for AsciiString {
699
+ type Output = AsciiString;
700
+
701
+ #[inline]
702
+ fn add(mut self, other: &AsciiStr) -> AsciiString {
703
+ self.push_str(other);
704
+ self
705
+ }
706
+ }
707
+
708
+ impl<'a> AddAssign<&'a AsciiStr> for AsciiString {
709
+ #[inline]
710
+ fn add_assign(&mut self, other: &AsciiStr) {
711
+ self.push_str(other);
712
+ }
713
+ }
714
+
715
+ #[allow(clippy::indexing_slicing)] // In `Index`, if it's out of bounds, panic is the default
716
+ impl<T> Index<T> for AsciiString
717
+ where
718
+ AsciiStr: Index<T>,
719
+ {
720
+ type Output = <AsciiStr as Index<T>>::Output;
721
+
722
+ #[inline]
723
+ fn index(&self, index: T) -> &<AsciiStr as Index<T>>::Output {
724
+ &(**self)[index]
725
+ }
726
+ }
727
+
728
+ #[allow(clippy::indexing_slicing)] // In `IndexMut`, if it's out of bounds, panic is the default
729
+ impl<T> IndexMut<T> for AsciiString
730
+ where
731
+ AsciiStr: IndexMut<T>,
732
+ {
733
+ #[inline]
734
+ fn index_mut(&mut self, index: T) -> &mut <AsciiStr as Index<T>>::Output {
735
+ &mut (**self)[index]
736
+ }
737
+ }
738
+
739
+ /// A possible error value when converting an `AsciiString` from a byte vector or string.
740
+ /// It wraps an `AsAsciiStrError` which you can get through the `ascii_error()` method.
741
+ ///
742
+ /// This is the error type for `AsciiString::from_ascii()` and
743
+ /// `IntoAsciiString::into_ascii_string()`. They will never clone or touch the content of the
744
+ /// original type; It can be extracted by the `into_source` method.
745
+ ///
746
+ /// #Examples
747
+ /// ```
748
+ /// # use ascii::IntoAsciiString;
749
+ /// let err = "bø!".to_string().into_ascii_string().unwrap_err();
750
+ /// assert_eq!(err.ascii_error().valid_up_to(), 1);
751
+ /// assert_eq!(err.into_source(), "bø!".to_string());
752
+ /// ```
753
+ #[derive(Clone, Copy, PartialEq, Eq)]
754
+ pub struct FromAsciiError<O> {
755
+ error: AsAsciiStrError,
756
+ owner: O,
757
+ }
758
+ impl<O> FromAsciiError<O> {
759
+ /// Get the position of the first non-ASCII byte or character.
760
+ #[inline]
761
+ #[must_use]
762
+ pub fn ascii_error(&self) -> AsAsciiStrError {
763
+ self.error
764
+ }
765
+ /// Get back the original, unmodified type.
766
+ #[inline]
767
+ #[must_use]
768
+ pub fn into_source(self) -> O {
769
+ self.owner
770
+ }
771
+ }
772
+ impl<O> fmt::Debug for FromAsciiError<O> {
773
+ #[inline]
774
+ fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
775
+ fmt::Debug::fmt(&self.error, fmtr)
776
+ }
777
+ }
778
+ impl<O> fmt::Display for FromAsciiError<O> {
779
+ #[inline]
780
+ fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
781
+ fmt::Display::fmt(&self.error, fmtr)
782
+ }
783
+ }
784
+ #[cfg(feature = "std")]
785
+ impl<O: Any> Error for FromAsciiError<O> {
786
+ #[inline]
787
+ #[allow(deprecated)] // TODO: Remove deprecation once the earliest version we support deprecates this method.
788
+ fn description(&self) -> &str {
789
+ self.error.description()
790
+ }
791
+ /// Always returns an `AsAsciiStrError`
792
+ fn cause(&self) -> Option<&dyn Error> {
793
+ Some(&self.error as &dyn Error)
794
+ }
795
+ }
796
+
797
+ /// Convert vectors into `AsciiString`.
798
+ pub trait IntoAsciiString: Sized {
799
+ /// Convert to `AsciiString` without checking for non-ASCII characters.
800
+ ///
801
+ /// # Safety
802
+ /// If `self` contains non-ascii characters, calling this function is
803
+ /// undefined behavior.
804
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString;
805
+
806
+ /// Convert to `AsciiString`.
807
+ ///
808
+ /// # Errors
809
+ /// If `self` contains non-ascii characters, this will return `Err`
810
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>>;
811
+ }
812
+
813
+ impl IntoAsciiString for Vec<AsciiChar> {
814
+ #[inline]
815
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
816
+ AsciiString::from(self)
817
+ }
818
+ #[inline]
819
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
820
+ Ok(AsciiString::from(self))
821
+ }
822
+ }
823
+
824
+ impl<'a> IntoAsciiString for &'a [AsciiChar] {
825
+ #[inline]
826
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
827
+ AsciiString::from(self)
828
+ }
829
+ #[inline]
830
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
831
+ Ok(AsciiString::from(self))
832
+ }
833
+ }
834
+
835
+ impl<'a> IntoAsciiString for &'a AsciiStr {
836
+ #[inline]
837
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
838
+ AsciiString::from(self)
839
+ }
840
+ #[inline]
841
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
842
+ Ok(AsciiString::from(self))
843
+ }
844
+ }
845
+
846
+ macro_rules! impl_into_ascii_string {
847
+ ('a, $wider:ty) => {
848
+ impl<'a> IntoAsciiString for $wider {
849
+ #[inline]
850
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
851
+ // SAFETY: Caller guarantees `self` only has valid ascii bytes
852
+ unsafe { AsciiString::from_ascii_unchecked(self) }
853
+ }
854
+
855
+ #[inline]
856
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
857
+ AsciiString::from_ascii(self)
858
+ }
859
+ }
860
+ };
861
+
862
+ ($wider:ty) => {
863
+ impl IntoAsciiString for $wider {
864
+ #[inline]
865
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
866
+ // SAFETY: Caller guarantees `self` only has valid ascii bytes
867
+ unsafe { AsciiString::from_ascii_unchecked(self) }
868
+ }
869
+
870
+ #[inline]
871
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
872
+ AsciiString::from_ascii(self)
873
+ }
874
+ }
875
+ };
876
+ }
877
+
878
+ impl_into_ascii_string! {AsciiString}
879
+ impl_into_ascii_string! {Vec<u8>}
880
+ impl_into_ascii_string! {'a, &'a [u8]}
881
+ impl_into_ascii_string! {String}
882
+ impl_into_ascii_string! {'a, &'a str}
883
+
884
+ /// # Notes
885
+ /// The trailing null byte `CString` has will be removed during this conversion.
886
+ #[cfg(feature = "std")]
887
+ impl IntoAsciiString for CString {
888
+ #[inline]
889
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
890
+ // SAFETY: Caller guarantees `self` only has valid ascii bytes
891
+ unsafe { AsciiString::from_ascii_unchecked(self.into_bytes()) }
892
+ }
893
+
894
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
895
+ AsciiString::from_ascii(self.into_bytes_with_nul())
896
+ .map_err(|FromAsciiError { error, owner }| {
897
+ FromAsciiError {
898
+ // SAFETY: We don't discard the NULL byte from the original
899
+ // string, so we ensure that it's null terminated
900
+ owner: unsafe { CString::from_vec_unchecked(owner) },
901
+ error,
902
+ }
903
+ })
904
+ .map(|mut s| {
905
+ let nul = s.pop();
906
+ debug_assert_eq!(nul, Some(AsciiChar::Null));
907
+ s
908
+ })
909
+ }
910
+ }
911
+
912
+ /// Note that the trailing null byte will be removed in the conversion.
913
+ #[cfg(feature = "std")]
914
+ impl<'a> IntoAsciiString for &'a CStr {
915
+ #[inline]
916
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
917
+ // SAFETY: Caller guarantees `self` only has valid ascii bytes
918
+ unsafe { AsciiString::from_ascii_unchecked(self.to_bytes()) }
919
+ }
920
+
921
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
922
+ AsciiString::from_ascii(self.to_bytes_with_nul())
923
+ .map_err(|FromAsciiError { error, owner }| FromAsciiError {
924
+ // SAFETY: We don't discard the NULL byte from the original
925
+ // string, so we ensure that it's null terminated
926
+ owner: unsafe { CStr::from_ptr(owner.as_ptr().cast()) },
927
+ error,
928
+ })
929
+ .map(|mut s| {
930
+ let nul = s.pop();
931
+ debug_assert_eq!(nul, Some(AsciiChar::Null));
932
+ s
933
+ })
934
+ }
935
+ }
936
+
937
+ impl<'a, B> IntoAsciiString for Cow<'a, B>
938
+ where
939
+ B: 'a + ToOwned + ?Sized,
940
+ &'a B: IntoAsciiString,
941
+ <B as ToOwned>::Owned: IntoAsciiString,
942
+ {
943
+ #[inline]
944
+ unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
945
+ // SAFETY: Caller guarantees `self` only has valid ascii bytes
946
+ unsafe { IntoAsciiString::into_ascii_string_unchecked(self.into_owned()) }
947
+ }
948
+
949
+ fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
950
+ match self {
951
+ Cow::Owned(b) => {
952
+ IntoAsciiString::into_ascii_string(b).map_err(|FromAsciiError { error, owner }| {
953
+ FromAsciiError {
954
+ owner: Cow::Owned(owner),
955
+ error,
956
+ }
957
+ })
958
+ }
959
+ Cow::Borrowed(b) => {
960
+ IntoAsciiString::into_ascii_string(b).map_err(|FromAsciiError { error, owner }| {
961
+ FromAsciiError {
962
+ owner: Cow::Borrowed(owner),
963
+ error,
964
+ }
965
+ })
966
+ }
967
+ }
968
+ }
969
+ }
970
+
971
+ #[cfg(test)]
972
+ mod tests {
973
+ use super::{AsciiString, IntoAsciiString};
974
+ use alloc::str::FromStr;
975
+ use alloc::string::{String, ToString};
976
+ use alloc::vec::Vec;
977
+ use alloc::boxed::Box;
978
+ #[cfg(feature = "std")]
979
+ use std::ffi::CString;
980
+ use {AsciiChar, AsciiStr};
981
+
982
+ #[test]
983
+ fn into_string() {
984
+ let v = AsciiString::from_ascii(&[40_u8, 32, 59][..]).unwrap();
985
+ assert_eq!(Into::<String>::into(v), "( ;".to_string());
986
+ }
987
+
988
+ #[test]
989
+ fn into_bytes() {
990
+ let v = AsciiString::from_ascii(&[40_u8, 32, 59][..]).unwrap();
991
+ assert_eq!(Into::<Vec<u8>>::into(v), vec![40_u8, 32, 59]);
992
+ }
993
+
994
+ #[test]
995
+ fn from_ascii_vec() {
996
+ let vec = vec![
997
+ AsciiChar::from_ascii('A').unwrap(),
998
+ AsciiChar::from_ascii('B').unwrap(),
999
+ ];
1000
+ assert_eq!(AsciiString::from(vec), AsciiString::from_str("AB").unwrap());
1001
+ }
1002
+
1003
+ #[test]
1004
+ #[cfg(feature = "std")]
1005
+ fn from_cstring() {
1006
+ let cstring = CString::new("baz").unwrap();
1007
+ let ascii_str = cstring.clone().into_ascii_string().unwrap();
1008
+ let expected_chars = &[AsciiChar::b, AsciiChar::a, AsciiChar::z];
1009
+ assert_eq!(ascii_str.len(), 3);
1010
+ assert_eq!(ascii_str.as_slice(), expected_chars);
1011
+
1012
+ // SAFETY: "baz" only contains valid ascii characters.
1013
+ let ascii_str_unchecked = unsafe { cstring.into_ascii_string_unchecked() };
1014
+ assert_eq!(ascii_str_unchecked.len(), 3);
1015
+ assert_eq!(ascii_str_unchecked.as_slice(), expected_chars);
1016
+
1017
+ let sparkle_heart_bytes = vec![240_u8, 159, 146, 150];
1018
+ let cstring = CString::new(sparkle_heart_bytes).unwrap();
1019
+ let cstr = &*cstring;
1020
+ let ascii_err = cstr.into_ascii_string().unwrap_err();
1021
+ assert_eq!(ascii_err.into_source(), &*cstring);
1022
+ }
1023
+
1024
+ #[test]
1025
+ #[cfg(feature = "std")]
1026
+ fn fmt_ascii_string() {
1027
+ let s = "abc".to_string().into_ascii_string().unwrap();
1028
+ assert_eq!(format!("{}", s), "abc".to_string());
1029
+ assert_eq!(format!("{:?}", s), "\"abc\"".to_string());
1030
+ }
1031
+
1032
+ #[test]
1033
+ fn write_fmt() {
1034
+ use alloc::{fmt, str};
1035
+
1036
+ let mut s0 = AsciiString::new();
1037
+ fmt::write(&mut s0, format_args!("Hello World")).unwrap();
1038
+ assert_eq!(s0, "Hello World");
1039
+
1040
+ let mut s1 = AsciiString::new();
1041
+ fmt::write(&mut s1, format_args!("{}", 9)).unwrap();
1042
+ assert_eq!(s1, "9");
1043
+
1044
+ let mut s2 = AsciiString::new();
1045
+ let sparkle_heart_bytes = [240, 159, 146, 150];
1046
+ let sparkle_heart = str::from_utf8(&sparkle_heart_bytes).unwrap();
1047
+ assert!(fmt::write(&mut s2, format_args!("{}", sparkle_heart)).is_err());
1048
+ }
1049
+
1050
+ #[test]
1051
+ fn to_and_from_box() {
1052
+ let string = "abc".into_ascii_string().unwrap();
1053
+ let converted: Box<AsciiStr> = Box::from(string.clone());
1054
+ let converted: AsciiString = converted.into();
1055
+ assert_eq!(string, converted);
1056
+ }
1057
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/free_functions.rs ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use ascii_char::{AsciiChar, ToAsciiChar};
2
+
3
+ /// Terminals use [caret notation](https://en.wikipedia.org/wiki/Caret_notation)
4
+ /// to display some typed control codes, such as ^D for EOT and ^Z for SUB.
5
+ ///
6
+ /// This function returns the caret notation letter for control codes,
7
+ /// or `None` for printable characters.
8
+ ///
9
+ /// # Examples
10
+ /// ```
11
+ /// # use ascii::{AsciiChar, caret_encode};
12
+ /// assert_eq!(caret_encode(b'\0'), Some(AsciiChar::At));
13
+ /// assert_eq!(caret_encode(AsciiChar::DEL), Some(AsciiChar::Question));
14
+ /// assert_eq!(caret_encode(b'E'), None);
15
+ /// assert_eq!(caret_encode(b'\n'), Some(AsciiChar::J));
16
+ /// ```
17
+ pub fn caret_encode<C: Copy + Into<u8>>(c: C) -> Option<AsciiChar> {
18
+ // The formula is explained in the Wikipedia article.
19
+ let c = c.into() ^ 0b0100_0000;
20
+ if (b'?'..=b'_').contains(&c) {
21
+ // SAFETY: All bytes between '?' (0x3F) and '_' (0x5f) are valid ascii characters.
22
+ Some(unsafe { c.to_ascii_char_unchecked() })
23
+ } else {
24
+ None
25
+ }
26
+ }
27
+
28
+ /// Returns the control code represented by a [caret notation](https://en.wikipedia.org/wiki/Caret_notation)
29
+ /// letter, or `None` if the letter is not used in caret notation.
30
+ ///
31
+ /// This function is the inverse of `caret_encode()`.
32
+ ///
33
+ /// # Examples
34
+ ///
35
+ /// Basic usage:
36
+ ///
37
+ /// ```
38
+ /// # use ascii::{AsciiChar, caret_decode};
39
+ /// assert_eq!(caret_decode(b'?'), Some(AsciiChar::DEL));
40
+ /// assert_eq!(caret_decode(AsciiChar::D), Some(AsciiChar::EOT));
41
+ /// assert_eq!(caret_decode(b'\0'), None);
42
+ /// ```
43
+ ///
44
+ /// Symmetry:
45
+ ///
46
+ /// ```
47
+ /// # use ascii::{AsciiChar, caret_encode, caret_decode};
48
+ /// assert_eq!(caret_encode(AsciiChar::US).and_then(caret_decode), Some(AsciiChar::US));
49
+ /// assert_eq!(caret_decode(b'@').and_then(caret_encode), Some(AsciiChar::At));
50
+ /// ```
51
+ pub fn caret_decode<C: Copy + Into<u8>>(c: C) -> Option<AsciiChar> {
52
+ // The formula is explained in the Wikipedia article.
53
+ match c.into() {
54
+ // SAFETY: All bytes between '?' (0x3F) and '_' (0x5f) after `xoring` with `0b0100_0000` are
55
+ // valid bytes, as they represent characters between '␀' (0x0) and '␠' (0x1f) + '␡' (0x7f)
56
+ b'?'..=b'_' => Some(unsafe { AsciiChar::from_ascii_unchecked(c.into() ^ 0b0100_0000) }),
57
+ _ => None,
58
+ }
59
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/lib.rs ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2
+ // file at the top-level directory of this distribution and at
3
+ // http://rust-lang.org/COPYRIGHT.
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6
+ // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7
+ // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8
+ // option. This file may not be copied, modified, or distributed
9
+ // except according to those terms.
10
+
11
+ //! A library that provides ASCII-only string and character types, equivalent to the `char`, `str`
12
+ //! and `String` types in the standard library.
13
+ //!
14
+ //! Please refer to the readme file to learn about the different feature modes of this crate.
15
+ //!
16
+ //! # Minimum supported Rust version
17
+ //!
18
+ //! The minimum Rust version for 1.1.\* releases is 1.41.1.
19
+ //! Later 1.y.0 releases might require newer Rust versions, but the three most
20
+ //! recent stable releases at the time of publishing will always be supported.
21
+ //! For example this means that if the current stable Rust version is 1.70 when
22
+ //! ascii 1.2.0 is released, then ascii 1.2.\* will not require a newer
23
+ //! Rust version than 1.68.
24
+ //!
25
+ //! # History
26
+ //!
27
+ //! This package included the Ascii types that were removed from the Rust standard library by the
28
+ //! 2014-12 [reform of the `std::ascii` module](https://github.com/rust-lang/rfcs/pull/486). The
29
+ //! API changed significantly since then.
30
+
31
+ #![cfg_attr(not(feature = "std"), no_std)]
32
+ // Clippy lints
33
+ #![warn(
34
+ clippy::pedantic,
35
+ clippy::decimal_literal_representation,
36
+ clippy::get_unwrap,
37
+ clippy::indexing_slicing
38
+ )]
39
+ // Naming conventions sometimes go against this lint
40
+ #![allow(clippy::module_name_repetitions)]
41
+ // We need to get literal non-asciis for tests
42
+ #![allow(clippy::non_ascii_literal)]
43
+ // Sometimes it looks better to invert the order, such as when the `else` block is small
44
+ #![allow(clippy::if_not_else)]
45
+ // Shadowing is common and doesn't affect understanding
46
+ // TODO: Consider removing `shadow_unrelated`, as it can show some actual logic errors
47
+ #![allow(clippy::shadow_unrelated, clippy::shadow_reuse, clippy::shadow_same)]
48
+ // A `if let` / `else` sometimes looks better than using iterator adaptors
49
+ #![allow(clippy::option_if_let_else)]
50
+ // In tests, we're fine with indexing, since a panic is a failure.
51
+ #![cfg_attr(test, allow(clippy::indexing_slicing))]
52
+ // for compatibility with methods on char and u8
53
+ #![allow(clippy::trivially_copy_pass_by_ref)]
54
+ // In preparation for feature `unsafe_block_in_unsafe_fn` (https://github.com/rust-lang/rust/issues/71668)
55
+ #![allow(unused_unsafe)]
56
+
57
+ #[cfg(feature = "alloc")]
58
+ #[macro_use]
59
+ extern crate alloc;
60
+ #[cfg(feature = "std")]
61
+ extern crate core;
62
+
63
+ #[cfg(feature = "serde")]
64
+ extern crate serde;
65
+
66
+ #[cfg(all(test, feature = "serde_test"))]
67
+ extern crate serde_test;
68
+
69
+ mod ascii_char;
70
+ mod ascii_str;
71
+ #[cfg(feature = "alloc")]
72
+ mod ascii_string;
73
+ mod free_functions;
74
+ #[cfg(feature = "serde")]
75
+ mod serialization;
76
+
77
+ pub use ascii_char::{AsciiChar, ToAsciiChar, ToAsciiCharError};
78
+ pub use ascii_str::{AsAsciiStr, AsAsciiStrError, AsMutAsciiStr, AsciiStr};
79
+ pub use ascii_str::{Chars, CharsMut, CharsRef};
80
+ #[cfg(feature = "alloc")]
81
+ pub use ascii_string::{AsciiString, FromAsciiError, IntoAsciiString};
82
+ pub use free_functions::{caret_decode, caret_encode};
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/serialization/ascii_char.rs ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::fmt;
2
+
3
+ use serde::de::{Error, Unexpected, Visitor};
4
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
5
+
6
+ use ascii_char::AsciiChar;
7
+
8
+ impl Serialize for AsciiChar {
9
+ #[inline]
10
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
11
+ serializer.serialize_char(self.as_char())
12
+ }
13
+ }
14
+
15
+ struct AsciiCharVisitor;
16
+
17
+ impl<'de> Visitor<'de> for AsciiCharVisitor {
18
+ type Value = AsciiChar;
19
+
20
+ fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
21
+ f.write_str("an ascii character")
22
+ }
23
+
24
+ #[inline]
25
+ fn visit_char<E: Error>(self, v: char) -> Result<Self::Value, E> {
26
+ AsciiChar::from_ascii(v).map_err(|_| Error::invalid_value(Unexpected::Char(v), &self))
27
+ }
28
+
29
+ #[inline]
30
+ fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
31
+ if v.len() == 1 {
32
+ let c = v.chars().next().unwrap();
33
+ self.visit_char(c)
34
+ } else {
35
+ Err(Error::invalid_value(Unexpected::Str(v), &self))
36
+ }
37
+ }
38
+ }
39
+
40
+ impl<'de> Deserialize<'de> for AsciiChar {
41
+ fn deserialize<D>(deserializer: D) -> Result<AsciiChar, D::Error>
42
+ where
43
+ D: Deserializer<'de>,
44
+ {
45
+ deserializer.deserialize_char(AsciiCharVisitor)
46
+ }
47
+ }
48
+
49
+ #[cfg(test)]
50
+ mod tests {
51
+ use super::*;
52
+
53
+ #[cfg(feature = "serde_test")]
54
+ const ASCII_CHAR: char = 'e';
55
+ #[cfg(feature = "serde_test")]
56
+ const ASCII_STR: &str = "e";
57
+ #[cfg(feature = "serde_test")]
58
+ const UNICODE_CHAR: char = 'é';
59
+
60
+ #[test]
61
+ fn basic() {
62
+ fn assert_serialize<T: Serialize>() {}
63
+ fn assert_deserialize<'de, T: Deserialize<'de>>() {}
64
+ assert_serialize::<AsciiChar>();
65
+ assert_deserialize::<AsciiChar>();
66
+ }
67
+
68
+ #[test]
69
+ #[cfg(feature = "serde_test")]
70
+ fn serialize() {
71
+ use serde_test::{assert_tokens, Token};
72
+ let ascii_char = AsciiChar::from_ascii(ASCII_CHAR).unwrap();
73
+ assert_tokens(&ascii_char, &[Token::Char(ASCII_CHAR)]);
74
+ }
75
+
76
+ #[test]
77
+ #[cfg(feature = "serde_test")]
78
+ fn deserialize() {
79
+ use serde_test::{assert_de_tokens, assert_de_tokens_error, Token};
80
+ let ascii_char = AsciiChar::from_ascii(ASCII_CHAR).unwrap();
81
+ assert_de_tokens(&ascii_char, &[Token::String(ASCII_STR)]);
82
+ assert_de_tokens(&ascii_char, &[Token::Str(ASCII_STR)]);
83
+ assert_de_tokens(&ascii_char, &[Token::BorrowedStr(ASCII_STR)]);
84
+ assert_de_tokens_error::<AsciiChar>(
85
+ &[Token::Char(UNICODE_CHAR)],
86
+ "invalid value: character `é`, expected an ascii character",
87
+ );
88
+ }
89
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/serialization/ascii_str.rs ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::fmt;
2
+
3
+ use serde::de::{Error, Unexpected, Visitor};
4
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
5
+
6
+ use ascii_str::AsciiStr;
7
+
8
+ impl Serialize for AsciiStr {
9
+ #[inline]
10
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
11
+ serializer.serialize_str(self.as_str())
12
+ }
13
+ }
14
+
15
+ struct AsciiStrVisitor;
16
+
17
+ impl<'a> Visitor<'a> for AsciiStrVisitor {
18
+ type Value = &'a AsciiStr;
19
+
20
+ fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
21
+ f.write_str("a borrowed ascii string")
22
+ }
23
+
24
+ fn visit_borrowed_str<E: Error>(self, v: &'a str) -> Result<Self::Value, E> {
25
+ AsciiStr::from_ascii(v.as_bytes())
26
+ .map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))
27
+ }
28
+
29
+ fn visit_borrowed_bytes<E: Error>(self, v: &'a [u8]) -> Result<Self::Value, E> {
30
+ AsciiStr::from_ascii(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
31
+ }
32
+ }
33
+
34
+ impl<'de: 'a, 'a> Deserialize<'de> for &'a AsciiStr {
35
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
36
+ where
37
+ D: Deserializer<'de>,
38
+ {
39
+ deserializer.deserialize_str(AsciiStrVisitor)
40
+ }
41
+ }
42
+
43
+ #[cfg(test)]
44
+ mod tests {
45
+ use super::*;
46
+
47
+ #[cfg(feature = "serde_test")]
48
+ const ASCII: &str = "Francais";
49
+ #[cfg(feature = "serde_test")]
50
+ const UNICODE: &str = "Français";
51
+
52
+ #[test]
53
+ fn basic() {
54
+ fn assert_serialize<T: Serialize>() {}
55
+ fn assert_deserialize<'de, T: Deserialize<'de>>() {}
56
+ assert_serialize::<&AsciiStr>();
57
+ assert_deserialize::<&AsciiStr>();
58
+ }
59
+
60
+ #[test]
61
+ #[cfg(feature = "serde_test")]
62
+ fn serialize() {
63
+ use serde_test::{assert_tokens, Token};
64
+ let ascii_str = AsciiStr::from_ascii(ASCII).unwrap();
65
+ assert_tokens(&ascii_str, &[Token::BorrowedStr(ASCII)]);
66
+ }
67
+
68
+ #[test]
69
+ #[cfg(feature = "serde_test")]
70
+ fn deserialize() {
71
+ use serde_test::{assert_de_tokens, assert_de_tokens_error, Token};
72
+ let ascii_str = AsciiStr::from_ascii(ASCII).unwrap();
73
+ assert_de_tokens(&ascii_str, &[Token::BorrowedBytes(ASCII.as_bytes())]);
74
+ assert_de_tokens_error::<&AsciiStr>(
75
+ &[Token::BorrowedStr(UNICODE)],
76
+ "invalid value: string \"Français\", expected a borrowed ascii string",
77
+ );
78
+ }
79
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/serialization/ascii_string.rs ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::fmt;
2
+
3
+ use serde::de::{Error, Unexpected, Visitor};
4
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
5
+
6
+ use ascii_str::AsciiStr;
7
+ use ascii_string::AsciiString;
8
+
9
+ impl Serialize for AsciiString {
10
+ #[inline]
11
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
12
+ serializer.serialize_str(self.as_str())
13
+ }
14
+ }
15
+
16
+ struct AsciiStringVisitor;
17
+
18
+ impl<'de> Visitor<'de> for AsciiStringVisitor {
19
+ type Value = AsciiString;
20
+
21
+ fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
22
+ f.write_str("an ascii string")
23
+ }
24
+
25
+ fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
26
+ AsciiString::from_ascii(v).map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))
27
+ }
28
+
29
+ fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
30
+ AsciiString::from_ascii(v.as_bytes())
31
+ .map_err(|_| Error::invalid_value(Unexpected::Str(&v), &self))
32
+ }
33
+
34
+ fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
35
+ AsciiString::from_ascii(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
36
+ }
37
+
38
+ fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
39
+ AsciiString::from_ascii(v.as_slice())
40
+ .map_err(|_| Error::invalid_value(Unexpected::Bytes(&v), &self))
41
+ }
42
+ }
43
+
44
+ struct AsciiStringInPlaceVisitor<'a>(&'a mut AsciiString);
45
+
46
+ impl<'a, 'de> Visitor<'de> for AsciiStringInPlaceVisitor<'a> {
47
+ type Value = ();
48
+
49
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
50
+ formatter.write_str("an ascii string")
51
+ }
52
+
53
+ fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
54
+ let ascii_str = match AsciiStr::from_ascii(v.as_bytes()) {
55
+ Ok(ascii_str) => ascii_str,
56
+ Err(_) => return Err(Error::invalid_value(Unexpected::Str(v), &self)),
57
+ };
58
+ self.0.clear();
59
+ self.0.push_str(ascii_str);
60
+ Ok(())
61
+ }
62
+
63
+ fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
64
+ let ascii_string = match AsciiString::from_ascii(v.as_bytes()) {
65
+ Ok(ascii_string) => ascii_string,
66
+ Err(_) => return Err(Error::invalid_value(Unexpected::Str(&v), &self)),
67
+ };
68
+ *self.0 = ascii_string;
69
+ Ok(())
70
+ }
71
+
72
+ fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
73
+ let ascii_str = match AsciiStr::from_ascii(v) {
74
+ Ok(ascii_str) => ascii_str,
75
+ Err(_) => return Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
76
+ };
77
+ self.0.clear();
78
+ self.0.push_str(ascii_str);
79
+ Ok(())
80
+ }
81
+
82
+ fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
83
+ let ascii_string = match AsciiString::from_ascii(v.as_slice()) {
84
+ Ok(ascii_string) => ascii_string,
85
+ Err(_) => return Err(Error::invalid_value(Unexpected::Bytes(&v), &self)),
86
+ };
87
+ *self.0 = ascii_string;
88
+ Ok(())
89
+ }
90
+ }
91
+
92
+ impl<'de> Deserialize<'de> for AsciiString {
93
+ fn deserialize<D>(deserializer: D) -> Result<AsciiString, D::Error>
94
+ where
95
+ D: Deserializer<'de>,
96
+ {
97
+ deserializer.deserialize_string(AsciiStringVisitor)
98
+ }
99
+
100
+ fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
101
+ where
102
+ D: Deserializer<'de>,
103
+ {
104
+ deserializer.deserialize_string(AsciiStringInPlaceVisitor(place))
105
+ }
106
+ }
107
+
108
+ #[cfg(test)]
109
+ mod tests {
110
+ use super::*;
111
+
112
+ #[cfg(feature = "serde_test")]
113
+ const ASCII: &str = "Francais";
114
+ #[cfg(feature = "serde_test")]
115
+ const UNICODE: &str = "Français";
116
+
117
+ #[test]
118
+ fn basic() {
119
+ fn assert_serialize<T: Serialize>() {}
120
+ fn assert_deserialize<'de, T: Deserialize<'de>>() {}
121
+ assert_serialize::<AsciiString>();
122
+ assert_deserialize::<AsciiString>();
123
+ }
124
+
125
+ #[test]
126
+ #[cfg(feature = "serde_test")]
127
+ fn serialize() {
128
+ use serde_test::{assert_tokens, Token};
129
+
130
+ let ascii_string = AsciiString::from_ascii(ASCII).unwrap();
131
+ assert_tokens(&ascii_string, &[Token::String(ASCII)]);
132
+ assert_tokens(&ascii_string, &[Token::Str(ASCII)]);
133
+ assert_tokens(&ascii_string, &[Token::BorrowedStr(ASCII)]);
134
+ }
135
+
136
+ #[test]
137
+ #[cfg(feature = "serde_test")]
138
+ fn deserialize() {
139
+ use serde_test::{assert_de_tokens, assert_de_tokens_error, Token};
140
+ let ascii_string = AsciiString::from_ascii(ASCII).unwrap();
141
+ assert_de_tokens(&ascii_string, &[Token::Bytes(ASCII.as_bytes())]);
142
+ assert_de_tokens(&ascii_string, &[Token::BorrowedBytes(ASCII.as_bytes())]);
143
+ assert_de_tokens(&ascii_string, &[Token::ByteBuf(ASCII.as_bytes())]);
144
+ assert_de_tokens_error::<AsciiString>(
145
+ &[Token::String(UNICODE)],
146
+ "invalid value: string \"Français\", expected an ascii string",
147
+ );
148
+ }
149
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ascii-1.1.0/src/serialization/mod.rs ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ mod ascii_char;
2
+ mod ascii_str;
3
+ mod ascii_string;
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/benches/defer.rs ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![feature(test)]
2
+
3
+ extern crate test;
4
+
5
+ use crossbeam_epoch::{self as epoch, Owned};
6
+ use crossbeam_utils::thread::scope;
7
+ use test::Bencher;
8
+
9
+ #[bench]
10
+ fn single_alloc_defer_free(b: &mut Bencher) {
11
+ b.iter(|| {
12
+ let guard = &epoch::pin();
13
+ let p = Owned::new(1).into_shared(guard);
14
+ unsafe {
15
+ guard.defer_destroy(p);
16
+ }
17
+ });
18
+ }
19
+
20
+ #[bench]
21
+ fn single_defer(b: &mut Bencher) {
22
+ b.iter(|| {
23
+ let guard = &epoch::pin();
24
+ guard.defer(move || ());
25
+ });
26
+ }
27
+
28
+ #[bench]
29
+ fn multi_alloc_defer_free(b: &mut Bencher) {
30
+ const THREADS: usize = 16;
31
+ const STEPS: usize = 10_000;
32
+
33
+ b.iter(|| {
34
+ scope(|s| {
35
+ for _ in 0..THREADS {
36
+ s.spawn(|_| {
37
+ for _ in 0..STEPS {
38
+ let guard = &epoch::pin();
39
+ let p = Owned::new(1).into_shared(guard);
40
+ unsafe {
41
+ guard.defer_destroy(p);
42
+ }
43
+ }
44
+ });
45
+ }
46
+ })
47
+ .unwrap();
48
+ });
49
+ }
50
+
51
+ #[bench]
52
+ fn multi_defer(b: &mut Bencher) {
53
+ const THREADS: usize = 16;
54
+ const STEPS: usize = 10_000;
55
+
56
+ b.iter(|| {
57
+ scope(|s| {
58
+ for _ in 0..THREADS {
59
+ s.spawn(|_| {
60
+ for _ in 0..STEPS {
61
+ let guard = &epoch::pin();
62
+ guard.defer(move || ());
63
+ }
64
+ });
65
+ }
66
+ })
67
+ .unwrap();
68
+ });
69
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/benches/flush.rs ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![feature(test)]
2
+
3
+ extern crate test;
4
+
5
+ use std::sync::Barrier;
6
+
7
+ use crossbeam_epoch as epoch;
8
+ use crossbeam_utils::thread::scope;
9
+ use test::Bencher;
10
+
11
+ #[bench]
12
+ fn single_flush(b: &mut Bencher) {
13
+ const THREADS: usize = 16;
14
+
15
+ let start = Barrier::new(THREADS + 1);
16
+ let end = Barrier::new(THREADS + 1);
17
+
18
+ scope(|s| {
19
+ for _ in 0..THREADS {
20
+ s.spawn(|_| {
21
+ epoch::pin();
22
+ start.wait();
23
+ end.wait();
24
+ });
25
+ }
26
+
27
+ start.wait();
28
+ b.iter(|| epoch::pin().flush());
29
+ end.wait();
30
+ })
31
+ .unwrap();
32
+ }
33
+
34
+ #[bench]
35
+ fn multi_flush(b: &mut Bencher) {
36
+ const THREADS: usize = 16;
37
+ const STEPS: usize = 10_000;
38
+
39
+ b.iter(|| {
40
+ scope(|s| {
41
+ for _ in 0..THREADS {
42
+ s.spawn(|_| {
43
+ for _ in 0..STEPS {
44
+ let guard = &epoch::pin();
45
+ guard.flush();
46
+ }
47
+ });
48
+ }
49
+ })
50
+ .unwrap();
51
+ });
52
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/benches/pin.rs ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![feature(test)]
2
+
3
+ extern crate test;
4
+
5
+ use crossbeam_epoch as epoch;
6
+ use crossbeam_utils::thread::scope;
7
+ use test::Bencher;
8
+
9
+ #[bench]
10
+ fn single_pin(b: &mut Bencher) {
11
+ b.iter(epoch::pin);
12
+ }
13
+
14
+ #[bench]
15
+ fn multi_pin(b: &mut Bencher) {
16
+ const THREADS: usize = 16;
17
+ const STEPS: usize = 100_000;
18
+
19
+ b.iter(|| {
20
+ scope(|s| {
21
+ for _ in 0..THREADS {
22
+ s.spawn(|_| {
23
+ for _ in 0..STEPS {
24
+ epoch::pin();
25
+ }
26
+ });
27
+ }
28
+ })
29
+ .unwrap();
30
+ });
31
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/examples/sanitize.rs ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::sync::atomic::AtomicUsize;
2
+ use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed};
3
+ use std::sync::Arc;
4
+ use std::thread;
5
+ use std::time::{Duration, Instant};
6
+
7
+ use crossbeam_epoch::{self as epoch, Atomic, Collector, LocalHandle, Owned, Shared};
8
+ use rand::Rng;
9
+
10
+ fn worker(a: Arc<Atomic<AtomicUsize>>, handle: LocalHandle) -> usize {
11
+ let mut rng = rand::thread_rng();
12
+ let mut sum = 0;
13
+
14
+ if rng.gen() {
15
+ thread::sleep(Duration::from_millis(1));
16
+ }
17
+ let timeout = Duration::from_millis(rng.gen_range(0..10));
18
+ let now = Instant::now();
19
+
20
+ while now.elapsed() < timeout {
21
+ for _ in 0..100 {
22
+ let guard = &handle.pin();
23
+ guard.flush();
24
+
25
+ let val = if rng.gen() {
26
+ let p = a.swap(Owned::new(AtomicUsize::new(sum)), AcqRel, guard);
27
+ unsafe {
28
+ guard.defer_destroy(p);
29
+ guard.flush();
30
+ p.deref().load(Relaxed)
31
+ }
32
+ } else {
33
+ let p = a.load(Acquire, guard);
34
+ unsafe { p.deref().fetch_add(sum, Relaxed) }
35
+ };
36
+
37
+ sum = sum.wrapping_add(val);
38
+ }
39
+ }
40
+
41
+ sum
42
+ }
43
+
44
+ fn main() {
45
+ for _ in 0..100 {
46
+ let collector = Collector::new();
47
+ let a = Arc::new(Atomic::new(AtomicUsize::new(777)));
48
+
49
+ let threads = (0..16)
50
+ .map(|_| {
51
+ let a = a.clone();
52
+ let c = collector.clone();
53
+ thread::spawn(move || worker(a, c.register()))
54
+ })
55
+ .collect::<Vec<_>>();
56
+
57
+ for t in threads {
58
+ t.join().unwrap();
59
+ }
60
+
61
+ unsafe {
62
+ a.swap(Shared::null(), AcqRel, epoch::unprotected())
63
+ .into_owned();
64
+ }
65
+ }
66
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/atomic.rs ADDED
@@ -0,0 +1,1702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use alloc::boxed::Box;
2
+ use core::alloc::Layout;
3
+ use core::borrow::{Borrow, BorrowMut};
4
+ use core::cmp;
5
+ use core::fmt;
6
+ use core::marker::PhantomData;
7
+ use core::mem::{self, MaybeUninit};
8
+ use core::ops::{Deref, DerefMut};
9
+ use core::ptr;
10
+ use core::slice;
11
+
12
+ use crate::guard::Guard;
13
+ use crate::primitive::sync::atomic::{AtomicUsize, Ordering};
14
+ use crossbeam_utils::atomic::AtomicConsume;
15
+
16
+ /// Given ordering for the success case in a compare-exchange operation, returns the strongest
17
+ /// appropriate ordering for the failure case.
18
+ #[inline]
19
+ fn strongest_failure_ordering(ord: Ordering) -> Ordering {
20
+ use self::Ordering::*;
21
+ match ord {
22
+ Relaxed | Release => Relaxed,
23
+ Acquire | AcqRel => Acquire,
24
+ _ => SeqCst,
25
+ }
26
+ }
27
+
28
+ /// The error returned on failed compare-and-set operation.
29
+ // TODO: remove in the next major version.
30
+ #[deprecated(note = "Use `CompareExchangeError` instead")]
31
+ pub type CompareAndSetError<'g, T, P> = CompareExchangeError<'g, T, P>;
32
+
33
+ /// The error returned on failed compare-and-swap operation.
34
+ pub struct CompareExchangeError<'g, T: ?Sized + Pointable, P: Pointer<T>> {
35
+ /// The value in the atomic pointer at the time of the failed operation.
36
+ pub current: Shared<'g, T>,
37
+
38
+ /// The new value, which the operation failed to store.
39
+ pub new: P,
40
+ }
41
+
42
+ impl<T, P: Pointer<T> + fmt::Debug> fmt::Debug for CompareExchangeError<'_, T, P> {
43
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44
+ f.debug_struct("CompareExchangeError")
45
+ .field("current", &self.current)
46
+ .field("new", &self.new)
47
+ .finish()
48
+ }
49
+ }
50
+
51
+ /// Memory orderings for compare-and-set operations.
52
+ ///
53
+ /// A compare-and-set operation can have different memory orderings depending on whether it
54
+ /// succeeds or fails. This trait generalizes different ways of specifying memory orderings.
55
+ ///
56
+ /// The two ways of specifying orderings for compare-and-set are:
57
+ ///
58
+ /// 1. Just one `Ordering` for the success case. In case of failure, the strongest appropriate
59
+ /// ordering is chosen.
60
+ /// 2. A pair of `Ordering`s. The first one is for the success case, while the second one is
61
+ /// for the failure case.
62
+ // TODO: remove in the next major version.
63
+ #[deprecated(
64
+ note = "`compare_and_set` and `compare_and_set_weak` that use this trait are deprecated, \
65
+ use `compare_exchange` or `compare_exchange_weak instead`"
66
+ )]
67
+ pub trait CompareAndSetOrdering {
68
+ /// The ordering of the operation when it succeeds.
69
+ fn success(&self) -> Ordering;
70
+
71
+ /// The ordering of the operation when it fails.
72
+ ///
73
+ /// The failure ordering can't be `Release` or `AcqRel` and must be equivalent or weaker than
74
+ /// the success ordering.
75
+ fn failure(&self) -> Ordering;
76
+ }
77
+
78
+ #[allow(deprecated)]
79
+ impl CompareAndSetOrdering for Ordering {
80
+ #[inline]
81
+ fn success(&self) -> Ordering {
82
+ *self
83
+ }
84
+
85
+ #[inline]
86
+ fn failure(&self) -> Ordering {
87
+ strongest_failure_ordering(*self)
88
+ }
89
+ }
90
+
91
+ #[allow(deprecated)]
92
+ impl CompareAndSetOrdering for (Ordering, Ordering) {
93
+ #[inline]
94
+ fn success(&self) -> Ordering {
95
+ self.0
96
+ }
97
+
98
+ #[inline]
99
+ fn failure(&self) -> Ordering {
100
+ self.1
101
+ }
102
+ }
103
+
104
+ /// Returns a bitmask containing the unused least significant bits of an aligned pointer to `T`.
105
+ #[inline]
106
+ fn low_bits<T: ?Sized + Pointable>() -> usize {
107
+ (1 << T::ALIGN.trailing_zeros()) - 1
108
+ }
109
+
110
+ /// Panics if the pointer is not properly unaligned.
111
+ #[inline]
112
+ fn ensure_aligned<T: ?Sized + Pointable>(raw: usize) {
113
+ assert_eq!(raw & low_bits::<T>(), 0, "unaligned pointer");
114
+ }
115
+
116
+ /// Given a tagged pointer `data`, returns the same pointer, but tagged with `tag`.
117
+ ///
118
+ /// `tag` is truncated to fit into the unused bits of the pointer to `T`.
119
+ #[inline]
120
+ fn compose_tag<T: ?Sized + Pointable>(data: usize, tag: usize) -> usize {
121
+ (data & !low_bits::<T>()) | (tag & low_bits::<T>())
122
+ }
123
+
124
+ /// Decomposes a tagged pointer `data` into the pointer and the tag.
125
+ #[inline]
126
+ fn decompose_tag<T: ?Sized + Pointable>(data: usize) -> (usize, usize) {
127
+ (data & !low_bits::<T>(), data & low_bits::<T>())
128
+ }
129
+
130
+ /// Types that are pointed to by a single word.
131
+ ///
132
+ /// In concurrent programming, it is necessary to represent an object within a word because atomic
133
+ /// operations (e.g., reads, writes, read-modify-writes) support only single words. This trait
134
+ /// qualifies such types that are pointed to by a single word.
135
+ ///
136
+ /// The trait generalizes `Box<T>` for a sized type `T`. In a box, an object of type `T` is
137
+ /// allocated in heap and it is owned by a single-word pointer. This trait is also implemented for
138
+ /// `[MaybeUninit<T>]` by storing its size along with its elements and pointing to the pair of array
139
+ /// size and elements.
140
+ ///
141
+ /// Pointers to `Pointable` types can be stored in [`Atomic`], [`Owned`], and [`Shared`]. In
142
+ /// particular, Crossbeam supports dynamically sized slices as follows.
143
+ ///
144
+ /// ```
145
+ /// use std::mem::MaybeUninit;
146
+ /// use crossbeam_epoch::Owned;
147
+ ///
148
+ /// let o = Owned::<[MaybeUninit<i32>]>::init(10); // allocating [i32; 10]
149
+ /// ```
150
+ pub trait Pointable {
151
+ /// The alignment of pointer.
152
+ const ALIGN: usize;
153
+
154
+ /// The type for initializers.
155
+ type Init;
156
+
157
+ /// Initializes a with the given initializer.
158
+ ///
159
+ /// # Safety
160
+ ///
161
+ /// The result should be a multiple of `ALIGN`.
162
+ unsafe fn init(init: Self::Init) -> usize;
163
+
164
+ /// Dereferences the given pointer.
165
+ ///
166
+ /// # Safety
167
+ ///
168
+ /// - The given `ptr` should have been initialized with [`Pointable::init`].
169
+ /// - `ptr` should not have yet been dropped by [`Pointable::drop`].
170
+ /// - `ptr` should not be mutably dereferenced by [`Pointable::deref_mut`] concurrently.
171
+ unsafe fn deref<'a>(ptr: usize) -> &'a Self;
172
+
173
+ /// Mutably dereferences the given pointer.
174
+ ///
175
+ /// # Safety
176
+ ///
177
+ /// - The given `ptr` should have been initialized with [`Pointable::init`].
178
+ /// - `ptr` should not have yet been dropped by [`Pointable::drop`].
179
+ /// - `ptr` should not be dereferenced by [`Pointable::deref`] or [`Pointable::deref_mut`]
180
+ /// concurrently.
181
+ unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut Self;
182
+
183
+ /// Drops the object pointed to by the given pointer.
184
+ ///
185
+ /// # Safety
186
+ ///
187
+ /// - The given `ptr` should have been initialized with [`Pointable::init`].
188
+ /// - `ptr` should not have yet been dropped by [`Pointable::drop`].
189
+ /// - `ptr` should not be dereferenced by [`Pointable::deref`] or [`Pointable::deref_mut`]
190
+ /// concurrently.
191
+ unsafe fn drop(ptr: usize);
192
+ }
193
+
194
+ impl<T> Pointable for T {
195
+ const ALIGN: usize = mem::align_of::<T>();
196
+
197
+ type Init = T;
198
+
199
+ unsafe fn init(init: Self::Init) -> usize {
200
+ Box::into_raw(Box::new(init)) as usize
201
+ }
202
+
203
+ unsafe fn deref<'a>(ptr: usize) -> &'a Self {
204
+ &*(ptr as *const T)
205
+ }
206
+
207
+ unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut Self {
208
+ &mut *(ptr as *mut T)
209
+ }
210
+
211
+ unsafe fn drop(ptr: usize) {
212
+ drop(Box::from_raw(ptr as *mut T));
213
+ }
214
+ }
215
+
216
+ /// Array with size.
217
+ ///
218
+ /// # Memory layout
219
+ ///
220
+ /// An array consisting of size and elements:
221
+ ///
222
+ /// ```text
223
+ /// elements
224
+ /// |
225
+ /// |
226
+ /// ------------------------------------
227
+ /// | size | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
228
+ /// ------------------------------------
229
+ /// ```
230
+ ///
231
+ /// Its memory layout is different from that of `Box<[T]>` in that size is in the allocation (not
232
+ /// along with pointer as in `Box<[T]>`).
233
+ ///
234
+ /// Elements are not present in the type, but they will be in the allocation.
235
+ /// ```
236
+ #[repr(C)]
237
+ struct Array<T> {
238
+ /// The number of elements (not the number of bytes).
239
+ len: usize,
240
+ elements: [MaybeUninit<T>; 0],
241
+ }
242
+
243
+ impl<T> Array<T> {
244
+ fn layout(len: usize) -> Layout {
245
+ Layout::new::<Self>()
246
+ .extend(Layout::array::<MaybeUninit<T>>(len).unwrap())
247
+ .unwrap()
248
+ .0
249
+ .pad_to_align()
250
+ }
251
+ }
252
+
253
+ impl<T> Pointable for [MaybeUninit<T>] {
254
+ const ALIGN: usize = mem::align_of::<Array<T>>();
255
+
256
+ type Init = usize;
257
+
258
+ unsafe fn init(len: Self::Init) -> usize {
259
+ let layout = Array::<T>::layout(len);
260
+ let ptr = alloc::alloc::alloc(layout).cast::<Array<T>>();
261
+ if ptr.is_null() {
262
+ alloc::alloc::handle_alloc_error(layout);
263
+ }
264
+ ptr::addr_of_mut!((*ptr).len).write(len);
265
+ ptr as usize
266
+ }
267
+
268
+ unsafe fn deref<'a>(ptr: usize) -> &'a Self {
269
+ let array = &*(ptr as *const Array<T>);
270
+ slice::from_raw_parts(array.elements.as_ptr() as *const _, array.len)
271
+ }
272
+
273
+ unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut Self {
274
+ let array = &*(ptr as *mut Array<T>);
275
+ slice::from_raw_parts_mut(array.elements.as_ptr() as *mut _, array.len)
276
+ }
277
+
278
+ unsafe fn drop(ptr: usize) {
279
+ let len = (*(ptr as *mut Array<T>)).len;
280
+ let layout = Array::<T>::layout(len);
281
+ alloc::alloc::dealloc(ptr as *mut u8, layout);
282
+ }
283
+ }
284
+
285
+ /// An atomic pointer that can be safely shared between threads.
286
+ ///
287
+ /// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
288
+ /// least significant bits of the address. For example, the tag for a pointer to a sized type `T`
289
+ /// should be less than `(1 << mem::align_of::<T>().trailing_zeros())`.
290
+ ///
291
+ /// Any method that loads the pointer must be passed a reference to a [`Guard`].
292
+ ///
293
+ /// Crossbeam supports dynamically sized types. See [`Pointable`] for details.
294
+ pub struct Atomic<T: ?Sized + Pointable> {
295
+ data: AtomicUsize,
296
+ _marker: PhantomData<*mut T>,
297
+ }
298
+
299
+ unsafe impl<T: ?Sized + Pointable + Send + Sync> Send for Atomic<T> {}
300
+ unsafe impl<T: ?Sized + Pointable + Send + Sync> Sync for Atomic<T> {}
301
+
302
+ impl<T> Atomic<T> {
303
+ /// Allocates `value` on the heap and returns a new atomic pointer pointing to it.
304
+ ///
305
+ /// # Examples
306
+ ///
307
+ /// ```
308
+ /// use crossbeam_epoch::Atomic;
309
+ ///
310
+ /// let a = Atomic::new(1234);
311
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
312
+ /// ```
313
+ pub fn new(init: T) -> Atomic<T> {
314
+ Self::init(init)
315
+ }
316
+ }
317
+
318
+ impl<T: ?Sized + Pointable> Atomic<T> {
319
+ /// Allocates `value` on the heap and returns a new atomic pointer pointing to it.
320
+ ///
321
+ /// # Examples
322
+ ///
323
+ /// ```
324
+ /// use crossbeam_epoch::Atomic;
325
+ ///
326
+ /// let a = Atomic::<i32>::init(1234);
327
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
328
+ /// ```
329
+ pub fn init(init: T::Init) -> Atomic<T> {
330
+ Self::from(Owned::init(init))
331
+ }
332
+
333
+ /// Returns a new atomic pointer pointing to the tagged pointer `data`.
334
+ fn from_usize(data: usize) -> Self {
335
+ Self {
336
+ data: AtomicUsize::new(data),
337
+ _marker: PhantomData,
338
+ }
339
+ }
340
+
341
+ /// Returns a new null atomic pointer.
342
+ ///
343
+ /// # Examples
344
+ ///
345
+ /// ```
346
+ /// use crossbeam_epoch::Atomic;
347
+ ///
348
+ /// let a = Atomic::<i32>::null();
349
+ /// ```
350
+ #[cfg(not(crossbeam_loom))]
351
+ pub const fn null() -> Atomic<T> {
352
+ Self {
353
+ data: AtomicUsize::new(0),
354
+ _marker: PhantomData,
355
+ }
356
+ }
357
+ /// Returns a new null atomic pointer.
358
+ #[cfg(crossbeam_loom)]
359
+ pub fn null() -> Atomic<T> {
360
+ Self {
361
+ data: AtomicUsize::new(0),
362
+ _marker: PhantomData,
363
+ }
364
+ }
365
+
366
+ /// Loads a `Shared` from the atomic pointer.
367
+ ///
368
+ /// This method takes an [`Ordering`] argument which describes the memory ordering of this
369
+ /// operation.
370
+ ///
371
+ /// # Examples
372
+ ///
373
+ /// ```
374
+ /// use crossbeam_epoch::{self as epoch, Atomic};
375
+ /// use std::sync::atomic::Ordering::SeqCst;
376
+ ///
377
+ /// let a = Atomic::new(1234);
378
+ /// let guard = &epoch::pin();
379
+ /// let p = a.load(SeqCst, guard);
380
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
381
+ /// ```
382
+ pub fn load<'g>(&self, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
383
+ unsafe { Shared::from_usize(self.data.load(ord)) }
384
+ }
385
+
386
+ /// Loads a `Shared` from the atomic pointer using a "consume" memory ordering.
387
+ ///
388
+ /// This is similar to the "acquire" ordering, except that an ordering is
389
+ /// only guaranteed with operations that "depend on" the result of the load.
390
+ /// However consume loads are usually much faster than acquire loads on
391
+ /// architectures with a weak memory model since they don't require memory
392
+ /// fence instructions.
393
+ ///
394
+ /// The exact definition of "depend on" is a bit vague, but it works as you
395
+ /// would expect in practice since a lot of software, especially the Linux
396
+ /// kernel, rely on this behavior.
397
+ ///
398
+ /// # Examples
399
+ ///
400
+ /// ```
401
+ /// use crossbeam_epoch::{self as epoch, Atomic};
402
+ ///
403
+ /// let a = Atomic::new(1234);
404
+ /// let guard = &epoch::pin();
405
+ /// let p = a.load_consume(guard);
406
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
407
+ /// ```
408
+ pub fn load_consume<'g>(&self, _: &'g Guard) -> Shared<'g, T> {
409
+ unsafe { Shared::from_usize(self.data.load_consume()) }
410
+ }
411
+
412
+ /// Stores a `Shared` or `Owned` pointer into the atomic pointer.
413
+ ///
414
+ /// This method takes an [`Ordering`] argument which describes the memory ordering of this
415
+ /// operation.
416
+ ///
417
+ /// # Examples
418
+ ///
419
+ /// ```
420
+ /// use crossbeam_epoch::{Atomic, Owned, Shared};
421
+ /// use std::sync::atomic::Ordering::SeqCst;
422
+ ///
423
+ /// let a = Atomic::new(1234);
424
+ /// # unsafe { drop(a.load(SeqCst, &crossbeam_epoch::pin()).into_owned()); } // avoid leak
425
+ /// a.store(Shared::null(), SeqCst);
426
+ /// a.store(Owned::new(1234), SeqCst);
427
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
428
+ /// ```
429
+ pub fn store<P: Pointer<T>>(&self, new: P, ord: Ordering) {
430
+ self.data.store(new.into_usize(), ord);
431
+ }
432
+
433
+ /// Stores a `Shared` or `Owned` pointer into the atomic pointer, returning the previous
434
+ /// `Shared`.
435
+ ///
436
+ /// This method takes an [`Ordering`] argument which describes the memory ordering of this
437
+ /// operation.
438
+ ///
439
+ /// # Examples
440
+ ///
441
+ /// ```
442
+ /// use crossbeam_epoch::{self as epoch, Atomic, Shared};
443
+ /// use std::sync::atomic::Ordering::SeqCst;
444
+ ///
445
+ /// let a = Atomic::new(1234);
446
+ /// let guard = &epoch::pin();
447
+ /// let p = a.swap(Shared::null(), SeqCst, guard);
448
+ /// # unsafe { drop(p.into_owned()); } // avoid leak
449
+ /// ```
450
+ pub fn swap<'g, P: Pointer<T>>(&self, new: P, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
451
+ unsafe { Shared::from_usize(self.data.swap(new.into_usize(), ord)) }
452
+ }
453
+
454
+ /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current
455
+ /// value is the same as `current`. The tag is also taken into account, so two pointers to the
456
+ /// same object, but with different tags, will not be considered equal.
457
+ ///
458
+ /// The return value is a result indicating whether the new pointer was written. On success the
459
+ /// pointer that was written is returned. On failure the actual current value and `new` are
460
+ /// returned.
461
+ ///
462
+ /// This method takes two `Ordering` arguments to describe the memory
463
+ /// ordering of this operation. `success` describes the required ordering for the
464
+ /// read-modify-write operation that takes place if the comparison with `current` succeeds.
465
+ /// `failure` describes the required ordering for the load operation that takes place when
466
+ /// the comparison fails. Using `Acquire` as success ordering makes the store part
467
+ /// of this operation `Relaxed`, and using `Release` makes the successful load
468
+ /// `Relaxed`. The failure ordering can only be `SeqCst`, `Acquire` or `Relaxed`
469
+ /// and must be equivalent to or weaker than the success ordering.
470
+ ///
471
+ /// # Examples
472
+ ///
473
+ /// ```
474
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared};
475
+ /// use std::sync::atomic::Ordering::SeqCst;
476
+ ///
477
+ /// let a = Atomic::new(1234);
478
+ ///
479
+ /// let guard = &epoch::pin();
480
+ /// let curr = a.load(SeqCst, guard);
481
+ /// let res1 = a.compare_exchange(curr, Shared::null(), SeqCst, SeqCst, guard);
482
+ /// let res2 = a.compare_exchange(curr, Owned::new(5678), SeqCst, SeqCst, guard);
483
+ /// # unsafe { drop(curr.into_owned()); } // avoid leak
484
+ /// ```
485
+ pub fn compare_exchange<'g, P>(
486
+ &self,
487
+ current: Shared<'_, T>,
488
+ new: P,
489
+ success: Ordering,
490
+ failure: Ordering,
491
+ _: &'g Guard,
492
+ ) -> Result<Shared<'g, T>, CompareExchangeError<'g, T, P>>
493
+ where
494
+ P: Pointer<T>,
495
+ {
496
+ let new = new.into_usize();
497
+ self.data
498
+ .compare_exchange(current.into_usize(), new, success, failure)
499
+ .map(|_| unsafe { Shared::from_usize(new) })
500
+ .map_err(|current| unsafe {
501
+ CompareExchangeError {
502
+ current: Shared::from_usize(current),
503
+ new: P::from_usize(new),
504
+ }
505
+ })
506
+ }
507
+
508
+ /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current
509
+ /// value is the same as `current`. The tag is also taken into account, so two pointers to the
510
+ /// same object, but with different tags, will not be considered equal.
511
+ ///
512
+ /// Unlike [`compare_exchange`], this method is allowed to spuriously fail even when comparison
513
+ /// succeeds, which can result in more efficient code on some platforms. The return value is a
514
+ /// result indicating whether the new pointer was written. On success the pointer that was
515
+ /// written is returned. On failure the actual current value and `new` are returned.
516
+ ///
517
+ /// This method takes two `Ordering` arguments to describe the memory
518
+ /// ordering of this operation. `success` describes the required ordering for the
519
+ /// read-modify-write operation that takes place if the comparison with `current` succeeds.
520
+ /// `failure` describes the required ordering for the load operation that takes place when
521
+ /// the comparison fails. Using `Acquire` as success ordering makes the store part
522
+ /// of this operation `Relaxed`, and using `Release` makes the successful load
523
+ /// `Relaxed`. The failure ordering can only be `SeqCst`, `Acquire` or `Relaxed`
524
+ /// and must be equivalent to or weaker than the success ordering.
525
+ ///
526
+ /// [`compare_exchange`]: Atomic::compare_exchange
527
+ ///
528
+ /// # Examples
529
+ ///
530
+ /// ```
531
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared};
532
+ /// use std::sync::atomic::Ordering::SeqCst;
533
+ ///
534
+ /// let a = Atomic::new(1234);
535
+ /// let guard = &epoch::pin();
536
+ ///
537
+ /// let mut new = Owned::new(5678);
538
+ /// let mut ptr = a.load(SeqCst, guard);
539
+ /// # unsafe { drop(a.load(SeqCst, guard).into_owned()); } // avoid leak
540
+ /// loop {
541
+ /// match a.compare_exchange_weak(ptr, new, SeqCst, SeqCst, guard) {
542
+ /// Ok(p) => {
543
+ /// ptr = p;
544
+ /// break;
545
+ /// }
546
+ /// Err(err) => {
547
+ /// ptr = err.current;
548
+ /// new = err.new;
549
+ /// }
550
+ /// }
551
+ /// }
552
+ ///
553
+ /// let mut curr = a.load(SeqCst, guard);
554
+ /// loop {
555
+ /// match a.compare_exchange_weak(curr, Shared::null(), SeqCst, SeqCst, guard) {
556
+ /// Ok(_) => break,
557
+ /// Err(err) => curr = err.current,
558
+ /// }
559
+ /// }
560
+ /// # unsafe { drop(curr.into_owned()); } // avoid leak
561
+ /// ```
562
+ pub fn compare_exchange_weak<'g, P>(
563
+ &self,
564
+ current: Shared<'_, T>,
565
+ new: P,
566
+ success: Ordering,
567
+ failure: Ordering,
568
+ _: &'g Guard,
569
+ ) -> Result<Shared<'g, T>, CompareExchangeError<'g, T, P>>
570
+ where
571
+ P: Pointer<T>,
572
+ {
573
+ let new = new.into_usize();
574
+ self.data
575
+ .compare_exchange_weak(current.into_usize(), new, success, failure)
576
+ .map(|_| unsafe { Shared::from_usize(new) })
577
+ .map_err(|current| unsafe {
578
+ CompareExchangeError {
579
+ current: Shared::from_usize(current),
580
+ new: P::from_usize(new),
581
+ }
582
+ })
583
+ }
584
+
585
+ /// Fetches the pointer, and then applies a function to it that returns a new value.
586
+ /// Returns a `Result` of `Ok(previous_value)` if the function returned `Some`, else `Err(_)`.
587
+ ///
588
+ /// Note that the given function may be called multiple times if the value has been changed by
589
+ /// other threads in the meantime, as long as the function returns `Some(_)`, but the function
590
+ /// will have been applied only once to the stored value.
591
+ ///
592
+ /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
593
+ /// ordering of this operation. The first describes the required ordering for
594
+ /// when the operation finally succeeds while the second describes the
595
+ /// required ordering for loads. These correspond to the success and failure
596
+ /// orderings of [`Atomic::compare_exchange`] respectively.
597
+ ///
598
+ /// Using [`Acquire`] as success ordering makes the store part of this
599
+ /// operation [`Relaxed`], and using [`Release`] makes the final successful
600
+ /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
601
+ /// [`Acquire`] or [`Relaxed`] and must be equivalent to or weaker than the
602
+ /// success ordering.
603
+ ///
604
+ /// [`Relaxed`]: Ordering::Relaxed
605
+ /// [`Acquire`]: Ordering::Acquire
606
+ /// [`Release`]: Ordering::Release
607
+ /// [`SeqCst`]: Ordering::SeqCst
608
+ ///
609
+ /// # Examples
610
+ ///
611
+ /// ```
612
+ /// use crossbeam_epoch::{self as epoch, Atomic};
613
+ /// use std::sync::atomic::Ordering::SeqCst;
614
+ ///
615
+ /// let a = Atomic::new(1234);
616
+ /// let guard = &epoch::pin();
617
+ ///
618
+ /// let res1 = a.fetch_update(SeqCst, SeqCst, guard, |x| Some(x.with_tag(1)));
619
+ /// assert!(res1.is_ok());
620
+ ///
621
+ /// let res2 = a.fetch_update(SeqCst, SeqCst, guard, |x| None);
622
+ /// assert!(res2.is_err());
623
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
624
+ /// ```
625
+ pub fn fetch_update<'g, F>(
626
+ &self,
627
+ set_order: Ordering,
628
+ fail_order: Ordering,
629
+ guard: &'g Guard,
630
+ mut func: F,
631
+ ) -> Result<Shared<'g, T>, Shared<'g, T>>
632
+ where
633
+ F: FnMut(Shared<'g, T>) -> Option<Shared<'g, T>>,
634
+ {
635
+ let mut prev = self.load(fail_order, guard);
636
+ while let Some(next) = func(prev) {
637
+ match self.compare_exchange_weak(prev, next, set_order, fail_order, guard) {
638
+ Ok(shared) => return Ok(shared),
639
+ Err(next_prev) => prev = next_prev.current,
640
+ }
641
+ }
642
+ Err(prev)
643
+ }
644
+
645
+ /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current
646
+ /// value is the same as `current`. The tag is also taken into account, so two pointers to the
647
+ /// same object, but with different tags, will not be considered equal.
648
+ ///
649
+ /// The return value is a result indicating whether the new pointer was written. On success the
650
+ /// pointer that was written is returned. On failure the actual current value and `new` are
651
+ /// returned.
652
+ ///
653
+ /// This method takes a [`CompareAndSetOrdering`] argument which describes the memory
654
+ /// ordering of this operation.
655
+ ///
656
+ /// # Migrating to `compare_exchange`
657
+ ///
658
+ /// `compare_and_set` is equivalent to `compare_exchange` with the following mapping for
659
+ /// memory orderings:
660
+ ///
661
+ /// Original | Success | Failure
662
+ /// -------- | ------- | -------
663
+ /// Relaxed | Relaxed | Relaxed
664
+ /// Acquire | Acquire | Acquire
665
+ /// Release | Release | Relaxed
666
+ /// AcqRel | AcqRel | Acquire
667
+ /// SeqCst | SeqCst | SeqCst
668
+ ///
669
+ /// # Examples
670
+ ///
671
+ /// ```
672
+ /// # #![allow(deprecated)]
673
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared};
674
+ /// use std::sync::atomic::Ordering::SeqCst;
675
+ ///
676
+ /// let a = Atomic::new(1234);
677
+ ///
678
+ /// let guard = &epoch::pin();
679
+ /// let curr = a.load(SeqCst, guard);
680
+ /// let res1 = a.compare_and_set(curr, Shared::null(), SeqCst, guard);
681
+ /// let res2 = a.compare_and_set(curr, Owned::new(5678), SeqCst, guard);
682
+ /// # unsafe { drop(curr.into_owned()); } // avoid leak
683
+ /// ```
684
+ // TODO: remove in the next major version.
685
+ #[allow(deprecated)]
686
+ #[deprecated(note = "Use `compare_exchange` instead")]
687
+ pub fn compare_and_set<'g, O, P>(
688
+ &self,
689
+ current: Shared<'_, T>,
690
+ new: P,
691
+ ord: O,
692
+ guard: &'g Guard,
693
+ ) -> Result<Shared<'g, T>, CompareAndSetError<'g, T, P>>
694
+ where
695
+ O: CompareAndSetOrdering,
696
+ P: Pointer<T>,
697
+ {
698
+ self.compare_exchange(current, new, ord.success(), ord.failure(), guard)
699
+ }
700
+
701
+ /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current
702
+ /// value is the same as `current`. The tag is also taken into account, so two pointers to the
703
+ /// same object, but with different tags, will not be considered equal.
704
+ ///
705
+ /// Unlike [`compare_and_set`], this method is allowed to spuriously fail even when comparison
706
+ /// succeeds, which can result in more efficient code on some platforms. The return value is a
707
+ /// result indicating whether the new pointer was written. On success the pointer that was
708
+ /// written is returned. On failure the actual current value and `new` are returned.
709
+ ///
710
+ /// This method takes a [`CompareAndSetOrdering`] argument which describes the memory
711
+ /// ordering of this operation.
712
+ ///
713
+ /// [`compare_and_set`]: Atomic::compare_and_set
714
+ ///
715
+ /// # Migrating to `compare_exchange_weak`
716
+ ///
717
+ /// `compare_and_set_weak` is equivalent to `compare_exchange_weak` with the following mapping for
718
+ /// memory orderings:
719
+ ///
720
+ /// Original | Success | Failure
721
+ /// -------- | ------- | -------
722
+ /// Relaxed | Relaxed | Relaxed
723
+ /// Acquire | Acquire | Acquire
724
+ /// Release | Release | Relaxed
725
+ /// AcqRel | AcqRel | Acquire
726
+ /// SeqCst | SeqCst | SeqCst
727
+ ///
728
+ /// # Examples
729
+ ///
730
+ /// ```
731
+ /// # #![allow(deprecated)]
732
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared};
733
+ /// use std::sync::atomic::Ordering::SeqCst;
734
+ ///
735
+ /// let a = Atomic::new(1234);
736
+ /// let guard = &epoch::pin();
737
+ ///
738
+ /// let mut new = Owned::new(5678);
739
+ /// let mut ptr = a.load(SeqCst, guard);
740
+ /// # unsafe { drop(a.load(SeqCst, guard).into_owned()); } // avoid leak
741
+ /// loop {
742
+ /// match a.compare_and_set_weak(ptr, new, SeqCst, guard) {
743
+ /// Ok(p) => {
744
+ /// ptr = p;
745
+ /// break;
746
+ /// }
747
+ /// Err(err) => {
748
+ /// ptr = err.current;
749
+ /// new = err.new;
750
+ /// }
751
+ /// }
752
+ /// }
753
+ ///
754
+ /// let mut curr = a.load(SeqCst, guard);
755
+ /// loop {
756
+ /// match a.compare_and_set_weak(curr, Shared::null(), SeqCst, guard) {
757
+ /// Ok(_) => break,
758
+ /// Err(err) => curr = err.current,
759
+ /// }
760
+ /// }
761
+ /// # unsafe { drop(curr.into_owned()); } // avoid leak
762
+ /// ```
763
+ // TODO: remove in the next major version.
764
+ #[allow(deprecated)]
765
+ #[deprecated(note = "Use `compare_exchange_weak` instead")]
766
+ pub fn compare_and_set_weak<'g, O, P>(
767
+ &self,
768
+ current: Shared<'_, T>,
769
+ new: P,
770
+ ord: O,
771
+ guard: &'g Guard,
772
+ ) -> Result<Shared<'g, T>, CompareAndSetError<'g, T, P>>
773
+ where
774
+ O: CompareAndSetOrdering,
775
+ P: Pointer<T>,
776
+ {
777
+ self.compare_exchange_weak(current, new, ord.success(), ord.failure(), guard)
778
+ }
779
+
780
+ /// Bitwise "and" with the current tag.
781
+ ///
782
+ /// Performs a bitwise "and" operation on the current tag and the argument `val`, and sets the
783
+ /// new tag to the result. Returns the previous pointer.
784
+ ///
785
+ /// This method takes an [`Ordering`] argument which describes the memory ordering of this
786
+ /// operation.
787
+ ///
788
+ /// # Examples
789
+ ///
790
+ /// ```
791
+ /// use crossbeam_epoch::{self as epoch, Atomic, Shared};
792
+ /// use std::sync::atomic::Ordering::SeqCst;
793
+ ///
794
+ /// let a = Atomic::<i32>::from(Shared::null().with_tag(3));
795
+ /// let guard = &epoch::pin();
796
+ /// assert_eq!(a.fetch_and(2, SeqCst, guard).tag(), 3);
797
+ /// assert_eq!(a.load(SeqCst, guard).tag(), 2);
798
+ /// ```
799
+ pub fn fetch_and<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
800
+ unsafe { Shared::from_usize(self.data.fetch_and(val | !low_bits::<T>(), ord)) }
801
+ }
802
+
803
+ /// Bitwise "or" with the current tag.
804
+ ///
805
+ /// Performs a bitwise "or" operation on the current tag and the argument `val`, and sets the
806
+ /// new tag to the result. Returns the previous pointer.
807
+ ///
808
+ /// This method takes an [`Ordering`] argument which describes the memory ordering of this
809
+ /// operation.
810
+ ///
811
+ /// # Examples
812
+ ///
813
+ /// ```
814
+ /// use crossbeam_epoch::{self as epoch, Atomic, Shared};
815
+ /// use std::sync::atomic::Ordering::SeqCst;
816
+ ///
817
+ /// let a = Atomic::<i32>::from(Shared::null().with_tag(1));
818
+ /// let guard = &epoch::pin();
819
+ /// assert_eq!(a.fetch_or(2, SeqCst, guard).tag(), 1);
820
+ /// assert_eq!(a.load(SeqCst, guard).tag(), 3);
821
+ /// ```
822
+ pub fn fetch_or<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
823
+ unsafe { Shared::from_usize(self.data.fetch_or(val & low_bits::<T>(), ord)) }
824
+ }
825
+
826
+ /// Bitwise "xor" with the current tag.
827
+ ///
828
+ /// Performs a bitwise "xor" operation on the current tag and the argument `val`, and sets the
829
+ /// new tag to the result. Returns the previous pointer.
830
+ ///
831
+ /// This method takes an [`Ordering`] argument which describes the memory ordering of this
832
+ /// operation.
833
+ ///
834
+ /// # Examples
835
+ ///
836
+ /// ```
837
+ /// use crossbeam_epoch::{self as epoch, Atomic, Shared};
838
+ /// use std::sync::atomic::Ordering::SeqCst;
839
+ ///
840
+ /// let a = Atomic::<i32>::from(Shared::null().with_tag(1));
841
+ /// let guard = &epoch::pin();
842
+ /// assert_eq!(a.fetch_xor(3, SeqCst, guard).tag(), 1);
843
+ /// assert_eq!(a.load(SeqCst, guard).tag(), 2);
844
+ /// ```
845
+ pub fn fetch_xor<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
846
+ unsafe { Shared::from_usize(self.data.fetch_xor(val & low_bits::<T>(), ord)) }
847
+ }
848
+
849
+ /// Takes ownership of the pointee.
850
+ ///
851
+ /// This consumes the atomic and converts it into [`Owned`]. As [`Atomic`] doesn't have a
852
+ /// destructor and doesn't drop the pointee while [`Owned`] does, this is suitable for
853
+ /// destructors of data structures.
854
+ ///
855
+ /// # Panics
856
+ ///
857
+ /// Panics if this pointer is null, but only in debug mode.
858
+ ///
859
+ /// # Safety
860
+ ///
861
+ /// This method may be called only if the pointer is valid and nobody else is holding a
862
+ /// reference to the same object.
863
+ ///
864
+ /// # Examples
865
+ ///
866
+ /// ```rust
867
+ /// # use std::mem;
868
+ /// # use crossbeam_epoch::Atomic;
869
+ /// struct DataStructure {
870
+ /// ptr: Atomic<usize>,
871
+ /// }
872
+ ///
873
+ /// impl Drop for DataStructure {
874
+ /// fn drop(&mut self) {
875
+ /// // By now the DataStructure lives only in our thread and we are sure we don't hold
876
+ /// // any Shared or & to it ourselves.
877
+ /// unsafe {
878
+ /// drop(mem::replace(&mut self.ptr, Atomic::null()).into_owned());
879
+ /// }
880
+ /// }
881
+ /// }
882
+ /// ```
883
+ pub unsafe fn into_owned(self) -> Owned<T> {
884
+ Owned::from_usize(self.data.into_inner())
885
+ }
886
+
887
+ /// Takes ownership of the pointee if it is non-null.
888
+ ///
889
+ /// This consumes the atomic and converts it into [`Owned`]. As [`Atomic`] doesn't have a
890
+ /// destructor and doesn't drop the pointee while [`Owned`] does, this is suitable for
891
+ /// destructors of data structures.
892
+ ///
893
+ /// # Safety
894
+ ///
895
+ /// This method may be called only if the pointer is valid and nobody else is holding a
896
+ /// reference to the same object, or the pointer is null.
897
+ ///
898
+ /// # Examples
899
+ ///
900
+ /// ```rust
901
+ /// # use std::mem;
902
+ /// # use crossbeam_epoch::Atomic;
903
+ /// struct DataStructure {
904
+ /// ptr: Atomic<usize>,
905
+ /// }
906
+ ///
907
+ /// impl Drop for DataStructure {
908
+ /// fn drop(&mut self) {
909
+ /// // By now the DataStructure lives only in our thread and we are sure we don't hold
910
+ /// // any Shared or & to it ourselves, but it may be null, so we have to be careful.
911
+ /// let old = mem::replace(&mut self.ptr, Atomic::null());
912
+ /// unsafe {
913
+ /// if let Some(x) = old.try_into_owned() {
914
+ /// drop(x)
915
+ /// }
916
+ /// }
917
+ /// }
918
+ /// }
919
+ /// ```
920
+ pub unsafe fn try_into_owned(self) -> Option<Owned<T>> {
921
+ let data = self.data.into_inner();
922
+ if decompose_tag::<T>(data).0 == 0 {
923
+ None
924
+ } else {
925
+ Some(Owned::from_usize(data))
926
+ }
927
+ }
928
+ }
929
+
930
+ impl<T: ?Sized + Pointable> fmt::Debug for Atomic<T> {
931
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
932
+ let data = self.data.load(Ordering::SeqCst);
933
+ let (raw, tag) = decompose_tag::<T>(data);
934
+
935
+ f.debug_struct("Atomic")
936
+ .field("raw", &raw)
937
+ .field("tag", &tag)
938
+ .finish()
939
+ }
940
+ }
941
+
942
+ impl<T: ?Sized + Pointable> fmt::Pointer for Atomic<T> {
943
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
944
+ let data = self.data.load(Ordering::SeqCst);
945
+ let (raw, _) = decompose_tag::<T>(data);
946
+ fmt::Pointer::fmt(&(unsafe { T::deref(raw) as *const _ }), f)
947
+ }
948
+ }
949
+
950
+ impl<T: ?Sized + Pointable> Clone for Atomic<T> {
951
+ /// Returns a copy of the atomic value.
952
+ ///
953
+ /// Note that a `Relaxed` load is used here. If you need synchronization, use it with other
954
+ /// atomics or fences.
955
+ fn clone(&self) -> Self {
956
+ let data = self.data.load(Ordering::Relaxed);
957
+ Atomic::from_usize(data)
958
+ }
959
+ }
960
+
961
+ impl<T: ?Sized + Pointable> Default for Atomic<T> {
962
+ fn default() -> Self {
963
+ Atomic::null()
964
+ }
965
+ }
966
+
967
+ impl<T: ?Sized + Pointable> From<Owned<T>> for Atomic<T> {
968
+ /// Returns a new atomic pointer pointing to `owned`.
969
+ ///
970
+ /// # Examples
971
+ ///
972
+ /// ```
973
+ /// use crossbeam_epoch::{Atomic, Owned};
974
+ ///
975
+ /// let a = Atomic::<i32>::from(Owned::new(1234));
976
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
977
+ /// ```
978
+ fn from(owned: Owned<T>) -> Self {
979
+ let data = owned.data;
980
+ mem::forget(owned);
981
+ Self::from_usize(data)
982
+ }
983
+ }
984
+
985
+ impl<T> From<Box<T>> for Atomic<T> {
986
+ fn from(b: Box<T>) -> Self {
987
+ Self::from(Owned::from(b))
988
+ }
989
+ }
990
+
991
+ impl<T> From<T> for Atomic<T> {
992
+ fn from(t: T) -> Self {
993
+ Self::new(t)
994
+ }
995
+ }
996
+
997
+ impl<'g, T: ?Sized + Pointable> From<Shared<'g, T>> for Atomic<T> {
998
+ /// Returns a new atomic pointer pointing to `ptr`.
999
+ ///
1000
+ /// # Examples
1001
+ ///
1002
+ /// ```
1003
+ /// use crossbeam_epoch::{Atomic, Shared};
1004
+ ///
1005
+ /// let a = Atomic::<i32>::from(Shared::<i32>::null());
1006
+ /// ```
1007
+ fn from(ptr: Shared<'g, T>) -> Self {
1008
+ Self::from_usize(ptr.data)
1009
+ }
1010
+ }
1011
+
1012
+ impl<T> From<*const T> for Atomic<T> {
1013
+ /// Returns a new atomic pointer pointing to `raw`.
1014
+ ///
1015
+ /// # Examples
1016
+ ///
1017
+ /// ```
1018
+ /// use std::ptr;
1019
+ /// use crossbeam_epoch::Atomic;
1020
+ ///
1021
+ /// let a = Atomic::<i32>::from(ptr::null::<i32>());
1022
+ /// ```
1023
+ fn from(raw: *const T) -> Self {
1024
+ Self::from_usize(raw as usize)
1025
+ }
1026
+ }
1027
+
1028
+ /// A trait for either `Owned` or `Shared` pointers.
1029
+ pub trait Pointer<T: ?Sized + Pointable> {
1030
+ /// Returns the machine representation of the pointer.
1031
+ fn into_usize(self) -> usize;
1032
+
1033
+ /// Returns a new pointer pointing to the tagged pointer `data`.
1034
+ ///
1035
+ /// # Safety
1036
+ ///
1037
+ /// The given `data` should have been created by `Pointer::into_usize()`, and one `data` should
1038
+ /// not be converted back by `Pointer::from_usize()` multiple times.
1039
+ unsafe fn from_usize(data: usize) -> Self;
1040
+ }
1041
+
1042
+ /// An owned heap-allocated object.
1043
+ ///
1044
+ /// This type is very similar to `Box<T>`.
1045
+ ///
1046
+ /// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
1047
+ /// least significant bits of the address.
1048
+ pub struct Owned<T: ?Sized + Pointable> {
1049
+ data: usize,
1050
+ _marker: PhantomData<Box<T>>,
1051
+ }
1052
+
1053
+ impl<T: ?Sized + Pointable> Pointer<T> for Owned<T> {
1054
+ #[inline]
1055
+ fn into_usize(self) -> usize {
1056
+ let data = self.data;
1057
+ mem::forget(self);
1058
+ data
1059
+ }
1060
+
1061
+ /// Returns a new pointer pointing to the tagged pointer `data`.
1062
+ ///
1063
+ /// # Panics
1064
+ ///
1065
+ /// Panics if the data is zero in debug mode.
1066
+ #[inline]
1067
+ unsafe fn from_usize(data: usize) -> Self {
1068
+ debug_assert!(data != 0, "converting zero into `Owned`");
1069
+ Owned {
1070
+ data,
1071
+ _marker: PhantomData,
1072
+ }
1073
+ }
1074
+ }
1075
+
1076
+ impl<T> Owned<T> {
1077
+ /// Returns a new owned pointer pointing to `raw`.
1078
+ ///
1079
+ /// This function is unsafe because improper use may lead to memory problems. Argument `raw`
1080
+ /// must be a valid pointer. Also, a double-free may occur if the function is called twice on
1081
+ /// the same raw pointer.
1082
+ ///
1083
+ /// # Panics
1084
+ ///
1085
+ /// Panics if `raw` is not properly aligned.
1086
+ ///
1087
+ /// # Safety
1088
+ ///
1089
+ /// The given `raw` should have been derived from `Owned`, and one `raw` should not be converted
1090
+ /// back by `Owned::from_raw()` multiple times.
1091
+ ///
1092
+ /// # Examples
1093
+ ///
1094
+ /// ```
1095
+ /// use crossbeam_epoch::Owned;
1096
+ ///
1097
+ /// let o = unsafe { Owned::from_raw(Box::into_raw(Box::new(1234))) };
1098
+ /// ```
1099
+ pub unsafe fn from_raw(raw: *mut T) -> Owned<T> {
1100
+ let raw = raw as usize;
1101
+ ensure_aligned::<T>(raw);
1102
+ Self::from_usize(raw)
1103
+ }
1104
+
1105
+ /// Converts the owned pointer into a `Box`.
1106
+ ///
1107
+ /// # Examples
1108
+ ///
1109
+ /// ```
1110
+ /// use crossbeam_epoch::Owned;
1111
+ ///
1112
+ /// let o = Owned::new(1234);
1113
+ /// let b: Box<i32> = o.into_box();
1114
+ /// assert_eq!(*b, 1234);
1115
+ /// ```
1116
+ pub fn into_box(self) -> Box<T> {
1117
+ let (raw, _) = decompose_tag::<T>(self.data);
1118
+ mem::forget(self);
1119
+ unsafe { Box::from_raw(raw as *mut _) }
1120
+ }
1121
+
1122
+ /// Allocates `value` on the heap and returns a new owned pointer pointing to it.
1123
+ ///
1124
+ /// # Examples
1125
+ ///
1126
+ /// ```
1127
+ /// use crossbeam_epoch::Owned;
1128
+ ///
1129
+ /// let o = Owned::new(1234);
1130
+ /// ```
1131
+ pub fn new(init: T) -> Owned<T> {
1132
+ Self::init(init)
1133
+ }
1134
+ }
1135
+
1136
+ impl<T: ?Sized + Pointable> Owned<T> {
1137
+ /// Allocates `value` on the heap and returns a new owned pointer pointing to it.
1138
+ ///
1139
+ /// # Examples
1140
+ ///
1141
+ /// ```
1142
+ /// use crossbeam_epoch::Owned;
1143
+ ///
1144
+ /// let o = Owned::<i32>::init(1234);
1145
+ /// ```
1146
+ pub fn init(init: T::Init) -> Owned<T> {
1147
+ unsafe { Self::from_usize(T::init(init)) }
1148
+ }
1149
+
1150
+ /// Converts the owned pointer into a [`Shared`].
1151
+ ///
1152
+ /// # Examples
1153
+ ///
1154
+ /// ```
1155
+ /// use crossbeam_epoch::{self as epoch, Owned};
1156
+ ///
1157
+ /// let o = Owned::new(1234);
1158
+ /// let guard = &epoch::pin();
1159
+ /// let p = o.into_shared(guard);
1160
+ /// # unsafe { drop(p.into_owned()); } // avoid leak
1161
+ /// ```
1162
+ #[allow(clippy::needless_lifetimes)]
1163
+ pub fn into_shared<'g>(self, _: &'g Guard) -> Shared<'g, T> {
1164
+ unsafe { Shared::from_usize(self.into_usize()) }
1165
+ }
1166
+
1167
+ /// Returns the tag stored within the pointer.
1168
+ ///
1169
+ /// # Examples
1170
+ ///
1171
+ /// ```
1172
+ /// use crossbeam_epoch::Owned;
1173
+ ///
1174
+ /// assert_eq!(Owned::new(1234).tag(), 0);
1175
+ /// ```
1176
+ pub fn tag(&self) -> usize {
1177
+ let (_, tag) = decompose_tag::<T>(self.data);
1178
+ tag
1179
+ }
1180
+
1181
+ /// Returns the same pointer, but tagged with `tag`. `tag` is truncated to be fit into the
1182
+ /// unused bits of the pointer to `T`.
1183
+ ///
1184
+ /// # Examples
1185
+ ///
1186
+ /// ```
1187
+ /// use crossbeam_epoch::Owned;
1188
+ ///
1189
+ /// let o = Owned::new(0u64);
1190
+ /// assert_eq!(o.tag(), 0);
1191
+ /// let o = o.with_tag(2);
1192
+ /// assert_eq!(o.tag(), 2);
1193
+ /// ```
1194
+ pub fn with_tag(self, tag: usize) -> Owned<T> {
1195
+ let data = self.into_usize();
1196
+ unsafe { Self::from_usize(compose_tag::<T>(data, tag)) }
1197
+ }
1198
+ }
1199
+
1200
+ impl<T: ?Sized + Pointable> Drop for Owned<T> {
1201
+ fn drop(&mut self) {
1202
+ let (raw, _) = decompose_tag::<T>(self.data);
1203
+ unsafe {
1204
+ T::drop(raw);
1205
+ }
1206
+ }
1207
+ }
1208
+
1209
+ impl<T: ?Sized + Pointable> fmt::Debug for Owned<T> {
1210
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1211
+ let (raw, tag) = decompose_tag::<T>(self.data);
1212
+
1213
+ f.debug_struct("Owned")
1214
+ .field("raw", &raw)
1215
+ .field("tag", &tag)
1216
+ .finish()
1217
+ }
1218
+ }
1219
+
1220
+ impl<T: Clone> Clone for Owned<T> {
1221
+ fn clone(&self) -> Self {
1222
+ Owned::new((**self).clone()).with_tag(self.tag())
1223
+ }
1224
+ }
1225
+
1226
+ impl<T: ?Sized + Pointable> Deref for Owned<T> {
1227
+ type Target = T;
1228
+
1229
+ fn deref(&self) -> &T {
1230
+ let (raw, _) = decompose_tag::<T>(self.data);
1231
+ unsafe { T::deref(raw) }
1232
+ }
1233
+ }
1234
+
1235
+ impl<T: ?Sized + Pointable> DerefMut for Owned<T> {
1236
+ fn deref_mut(&mut self) -> &mut T {
1237
+ let (raw, _) = decompose_tag::<T>(self.data);
1238
+ unsafe { T::deref_mut(raw) }
1239
+ }
1240
+ }
1241
+
1242
+ impl<T> From<T> for Owned<T> {
1243
+ fn from(t: T) -> Self {
1244
+ Owned::new(t)
1245
+ }
1246
+ }
1247
+
1248
+ impl<T> From<Box<T>> for Owned<T> {
1249
+ /// Returns a new owned pointer pointing to `b`.
1250
+ ///
1251
+ /// # Panics
1252
+ ///
1253
+ /// Panics if the pointer (the `Box`) is not properly aligned.
1254
+ ///
1255
+ /// # Examples
1256
+ ///
1257
+ /// ```
1258
+ /// use crossbeam_epoch::Owned;
1259
+ ///
1260
+ /// let o = unsafe { Owned::from_raw(Box::into_raw(Box::new(1234))) };
1261
+ /// ```
1262
+ fn from(b: Box<T>) -> Self {
1263
+ unsafe { Self::from_raw(Box::into_raw(b)) }
1264
+ }
1265
+ }
1266
+
1267
+ impl<T: ?Sized + Pointable> Borrow<T> for Owned<T> {
1268
+ fn borrow(&self) -> &T {
1269
+ self.deref()
1270
+ }
1271
+ }
1272
+
1273
+ impl<T: ?Sized + Pointable> BorrowMut<T> for Owned<T> {
1274
+ fn borrow_mut(&mut self) -> &mut T {
1275
+ self.deref_mut()
1276
+ }
1277
+ }
1278
+
1279
+ impl<T: ?Sized + Pointable> AsRef<T> for Owned<T> {
1280
+ fn as_ref(&self) -> &T {
1281
+ self.deref()
1282
+ }
1283
+ }
1284
+
1285
+ impl<T: ?Sized + Pointable> AsMut<T> for Owned<T> {
1286
+ fn as_mut(&mut self) -> &mut T {
1287
+ self.deref_mut()
1288
+ }
1289
+ }
1290
+
1291
+ /// A pointer to an object protected by the epoch GC.
1292
+ ///
1293
+ /// The pointer is valid for use only during the lifetime `'g`.
1294
+ ///
1295
+ /// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
1296
+ /// least significant bits of the address.
1297
+ pub struct Shared<'g, T: 'g + ?Sized + Pointable> {
1298
+ data: usize,
1299
+ _marker: PhantomData<(&'g (), *const T)>,
1300
+ }
1301
+
1302
+ impl<T: ?Sized + Pointable> Clone for Shared<'_, T> {
1303
+ fn clone(&self) -> Self {
1304
+ *self
1305
+ }
1306
+ }
1307
+
1308
+ impl<T: ?Sized + Pointable> Copy for Shared<'_, T> {}
1309
+
1310
+ impl<T: ?Sized + Pointable> Pointer<T> for Shared<'_, T> {
1311
+ #[inline]
1312
+ fn into_usize(self) -> usize {
1313
+ self.data
1314
+ }
1315
+
1316
+ #[inline]
1317
+ unsafe fn from_usize(data: usize) -> Self {
1318
+ Shared {
1319
+ data,
1320
+ _marker: PhantomData,
1321
+ }
1322
+ }
1323
+ }
1324
+
1325
+ impl<'g, T> Shared<'g, T> {
1326
+ /// Converts the pointer to a raw pointer (without the tag).
1327
+ ///
1328
+ /// # Examples
1329
+ ///
1330
+ /// ```
1331
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
1332
+ /// use std::sync::atomic::Ordering::SeqCst;
1333
+ ///
1334
+ /// let o = Owned::new(1234);
1335
+ /// let raw = &*o as *const _;
1336
+ /// let a = Atomic::from(o);
1337
+ ///
1338
+ /// let guard = &epoch::pin();
1339
+ /// let p = a.load(SeqCst, guard);
1340
+ /// assert_eq!(p.as_raw(), raw);
1341
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
1342
+ /// ```
1343
+ pub fn as_raw(&self) -> *const T {
1344
+ let (raw, _) = decompose_tag::<T>(self.data);
1345
+ raw as *const _
1346
+ }
1347
+ }
1348
+
1349
+ impl<'g, T: ?Sized + Pointable> Shared<'g, T> {
1350
+ /// Returns a new null pointer.
1351
+ ///
1352
+ /// # Examples
1353
+ ///
1354
+ /// ```
1355
+ /// use crossbeam_epoch::Shared;
1356
+ ///
1357
+ /// let p = Shared::<i32>::null();
1358
+ /// assert!(p.is_null());
1359
+ /// ```
1360
+ pub fn null() -> Shared<'g, T> {
1361
+ Shared {
1362
+ data: 0,
1363
+ _marker: PhantomData,
1364
+ }
1365
+ }
1366
+
1367
+ /// Returns `true` if the pointer is null.
1368
+ ///
1369
+ /// # Examples
1370
+ ///
1371
+ /// ```
1372
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
1373
+ /// use std::sync::atomic::Ordering::SeqCst;
1374
+ ///
1375
+ /// let a = Atomic::null();
1376
+ /// let guard = &epoch::pin();
1377
+ /// assert!(a.load(SeqCst, guard).is_null());
1378
+ /// a.store(Owned::new(1234), SeqCst);
1379
+ /// assert!(!a.load(SeqCst, guard).is_null());
1380
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
1381
+ /// ```
1382
+ pub fn is_null(&self) -> bool {
1383
+ let (raw, _) = decompose_tag::<T>(self.data);
1384
+ raw == 0
1385
+ }
1386
+
1387
+ /// Dereferences the pointer.
1388
+ ///
1389
+ /// Returns a reference to the pointee that is valid during the lifetime `'g`.
1390
+ ///
1391
+ /// # Safety
1392
+ ///
1393
+ /// Dereferencing a pointer is unsafe because it could be pointing to invalid memory.
1394
+ ///
1395
+ /// Another concern is the possibility of data races due to lack of proper synchronization.
1396
+ /// For example, consider the following scenario:
1397
+ ///
1398
+ /// 1. A thread creates a new object: `a.store(Owned::new(10), Relaxed)`
1399
+ /// 2. Another thread reads it: `*a.load(Relaxed, guard).as_ref().unwrap()`
1400
+ ///
1401
+ /// The problem is that relaxed orderings don't synchronize initialization of the object with
1402
+ /// the read from the second thread. This is a data race. A possible solution would be to use
1403
+ /// `Release` and `Acquire` orderings.
1404
+ ///
1405
+ /// # Examples
1406
+ ///
1407
+ /// ```
1408
+ /// use crossbeam_epoch::{self as epoch, Atomic};
1409
+ /// use std::sync::atomic::Ordering::SeqCst;
1410
+ ///
1411
+ /// let a = Atomic::new(1234);
1412
+ /// let guard = &epoch::pin();
1413
+ /// let p = a.load(SeqCst, guard);
1414
+ /// unsafe {
1415
+ /// assert_eq!(p.deref(), &1234);
1416
+ /// }
1417
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
1418
+ /// ```
1419
+ pub unsafe fn deref(&self) -> &'g T {
1420
+ let (raw, _) = decompose_tag::<T>(self.data);
1421
+ T::deref(raw)
1422
+ }
1423
+
1424
+ /// Dereferences the pointer.
1425
+ ///
1426
+ /// Returns a mutable reference to the pointee that is valid during the lifetime `'g`.
1427
+ ///
1428
+ /// # Safety
1429
+ ///
1430
+ /// * There is no guarantee that there are no more threads attempting to read/write from/to the
1431
+ /// actual object at the same time.
1432
+ ///
1433
+ /// The user must know that there are no concurrent accesses towards the object itself.
1434
+ ///
1435
+ /// * Other than the above, all safety concerns of `deref()` applies here.
1436
+ ///
1437
+ /// # Examples
1438
+ ///
1439
+ /// ```
1440
+ /// use crossbeam_epoch::{self as epoch, Atomic};
1441
+ /// use std::sync::atomic::Ordering::SeqCst;
1442
+ ///
1443
+ /// let a = Atomic::new(vec![1, 2, 3, 4]);
1444
+ /// let guard = &epoch::pin();
1445
+ ///
1446
+ /// let mut p = a.load(SeqCst, guard);
1447
+ /// unsafe {
1448
+ /// assert!(!p.is_null());
1449
+ /// let b = p.deref_mut();
1450
+ /// assert_eq!(b, &vec![1, 2, 3, 4]);
1451
+ /// b.push(5);
1452
+ /// assert_eq!(b, &vec![1, 2, 3, 4, 5]);
1453
+ /// }
1454
+ ///
1455
+ /// let p = a.load(SeqCst, guard);
1456
+ /// unsafe {
1457
+ /// assert_eq!(p.deref(), &vec![1, 2, 3, 4, 5]);
1458
+ /// }
1459
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
1460
+ /// ```
1461
+ pub unsafe fn deref_mut(&mut self) -> &'g mut T {
1462
+ let (raw, _) = decompose_tag::<T>(self.data);
1463
+ T::deref_mut(raw)
1464
+ }
1465
+
1466
+ /// Converts the pointer to a reference.
1467
+ ///
1468
+ /// Returns `None` if the pointer is null, or else a reference to the object wrapped in `Some`.
1469
+ ///
1470
+ /// # Safety
1471
+ ///
1472
+ /// Dereferencing a pointer is unsafe because it could be pointing to invalid memory.
1473
+ ///
1474
+ /// Another concern is the possibility of data races due to lack of proper synchronization.
1475
+ /// For example, consider the following scenario:
1476
+ ///
1477
+ /// 1. A thread creates a new object: `a.store(Owned::new(10), Relaxed)`
1478
+ /// 2. Another thread reads it: `*a.load(Relaxed, guard).as_ref().unwrap()`
1479
+ ///
1480
+ /// The problem is that relaxed orderings don't synchronize initialization of the object with
1481
+ /// the read from the second thread. This is a data race. A possible solution would be to use
1482
+ /// `Release` and `Acquire` orderings.
1483
+ ///
1484
+ /// # Examples
1485
+ ///
1486
+ /// ```
1487
+ /// use crossbeam_epoch::{self as epoch, Atomic};
1488
+ /// use std::sync::atomic::Ordering::SeqCst;
1489
+ ///
1490
+ /// let a = Atomic::new(1234);
1491
+ /// let guard = &epoch::pin();
1492
+ /// let p = a.load(SeqCst, guard);
1493
+ /// unsafe {
1494
+ /// assert_eq!(p.as_ref(), Some(&1234));
1495
+ /// }
1496
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
1497
+ /// ```
1498
+ pub unsafe fn as_ref(&self) -> Option<&'g T> {
1499
+ let (raw, _) = decompose_tag::<T>(self.data);
1500
+ if raw == 0 {
1501
+ None
1502
+ } else {
1503
+ Some(T::deref(raw))
1504
+ }
1505
+ }
1506
+
1507
+ /// Takes ownership of the pointee.
1508
+ ///
1509
+ /// # Panics
1510
+ ///
1511
+ /// Panics if this pointer is null, but only in debug mode.
1512
+ ///
1513
+ /// # Safety
1514
+ ///
1515
+ /// This method may be called only if the pointer is valid and nobody else is holding a
1516
+ /// reference to the same object.
1517
+ ///
1518
+ /// # Examples
1519
+ ///
1520
+ /// ```
1521
+ /// use crossbeam_epoch::{self as epoch, Atomic};
1522
+ /// use std::sync::atomic::Ordering::SeqCst;
1523
+ ///
1524
+ /// let a = Atomic::new(1234);
1525
+ /// unsafe {
1526
+ /// let guard = &epoch::unprotected();
1527
+ /// let p = a.load(SeqCst, guard);
1528
+ /// drop(p.into_owned());
1529
+ /// }
1530
+ /// ```
1531
+ pub unsafe fn into_owned(self) -> Owned<T> {
1532
+ debug_assert!(!self.is_null(), "converting a null `Shared` into `Owned`");
1533
+ Owned::from_usize(self.data)
1534
+ }
1535
+
1536
+ /// Takes ownership of the pointee if it is not null.
1537
+ ///
1538
+ /// # Safety
1539
+ ///
1540
+ /// This method may be called only if the pointer is valid and nobody else is holding a
1541
+ /// reference to the same object, or if the pointer is null.
1542
+ ///
1543
+ /// # Examples
1544
+ ///
1545
+ /// ```
1546
+ /// use crossbeam_epoch::{self as epoch, Atomic};
1547
+ /// use std::sync::atomic::Ordering::SeqCst;
1548
+ ///
1549
+ /// let a = Atomic::new(1234);
1550
+ /// unsafe {
1551
+ /// let guard = &epoch::unprotected();
1552
+ /// let p = a.load(SeqCst, guard);
1553
+ /// if let Some(x) = p.try_into_owned() {
1554
+ /// drop(x);
1555
+ /// }
1556
+ /// }
1557
+ /// ```
1558
+ pub unsafe fn try_into_owned(self) -> Option<Owned<T>> {
1559
+ if self.is_null() {
1560
+ None
1561
+ } else {
1562
+ Some(Owned::from_usize(self.data))
1563
+ }
1564
+ }
1565
+
1566
+ /// Returns the tag stored within the pointer.
1567
+ ///
1568
+ /// # Examples
1569
+ ///
1570
+ /// ```
1571
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
1572
+ /// use std::sync::atomic::Ordering::SeqCst;
1573
+ ///
1574
+ /// let a = Atomic::<u64>::from(Owned::new(0u64).with_tag(2));
1575
+ /// let guard = &epoch::pin();
1576
+ /// let p = a.load(SeqCst, guard);
1577
+ /// assert_eq!(p.tag(), 2);
1578
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
1579
+ /// ```
1580
+ pub fn tag(&self) -> usize {
1581
+ let (_, tag) = decompose_tag::<T>(self.data);
1582
+ tag
1583
+ }
1584
+
1585
+ /// Returns the same pointer, but tagged with `tag`. `tag` is truncated to be fit into the
1586
+ /// unused bits of the pointer to `T`.
1587
+ ///
1588
+ /// # Examples
1589
+ ///
1590
+ /// ```
1591
+ /// use crossbeam_epoch::{self as epoch, Atomic};
1592
+ /// use std::sync::atomic::Ordering::SeqCst;
1593
+ ///
1594
+ /// let a = Atomic::new(0u64);
1595
+ /// let guard = &epoch::pin();
1596
+ /// let p1 = a.load(SeqCst, guard);
1597
+ /// let p2 = p1.with_tag(2);
1598
+ ///
1599
+ /// assert_eq!(p1.tag(), 0);
1600
+ /// assert_eq!(p2.tag(), 2);
1601
+ /// assert_eq!(p1.as_raw(), p2.as_raw());
1602
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
1603
+ /// ```
1604
+ pub fn with_tag(&self, tag: usize) -> Shared<'g, T> {
1605
+ unsafe { Self::from_usize(compose_tag::<T>(self.data, tag)) }
1606
+ }
1607
+ }
1608
+
1609
+ impl<T> From<*const T> for Shared<'_, T> {
1610
+ /// Returns a new pointer pointing to `raw`.
1611
+ ///
1612
+ /// # Panics
1613
+ ///
1614
+ /// Panics if `raw` is not properly aligned.
1615
+ ///
1616
+ /// # Examples
1617
+ ///
1618
+ /// ```
1619
+ /// use crossbeam_epoch::Shared;
1620
+ ///
1621
+ /// let p = Shared::from(Box::into_raw(Box::new(1234)) as *const _);
1622
+ /// assert!(!p.is_null());
1623
+ /// # unsafe { drop(p.into_owned()); } // avoid leak
1624
+ /// ```
1625
+ fn from(raw: *const T) -> Self {
1626
+ let raw = raw as usize;
1627
+ ensure_aligned::<T>(raw);
1628
+ unsafe { Self::from_usize(raw) }
1629
+ }
1630
+ }
1631
+
1632
+ impl<'g, T: ?Sized + Pointable> PartialEq<Shared<'g, T>> for Shared<'g, T> {
1633
+ fn eq(&self, other: &Self) -> bool {
1634
+ self.data == other.data
1635
+ }
1636
+ }
1637
+
1638
+ impl<T: ?Sized + Pointable> Eq for Shared<'_, T> {}
1639
+
1640
+ impl<'g, T: ?Sized + Pointable> PartialOrd<Shared<'g, T>> for Shared<'g, T> {
1641
+ fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1642
+ self.data.partial_cmp(&other.data)
1643
+ }
1644
+ }
1645
+
1646
+ impl<T: ?Sized + Pointable> Ord for Shared<'_, T> {
1647
+ fn cmp(&self, other: &Self) -> cmp::Ordering {
1648
+ self.data.cmp(&other.data)
1649
+ }
1650
+ }
1651
+
1652
+ impl<T: ?Sized + Pointable> fmt::Debug for Shared<'_, T> {
1653
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1654
+ let (raw, tag) = decompose_tag::<T>(self.data);
1655
+
1656
+ f.debug_struct("Shared")
1657
+ .field("raw", &raw)
1658
+ .field("tag", &tag)
1659
+ .finish()
1660
+ }
1661
+ }
1662
+
1663
+ impl<T: ?Sized + Pointable> fmt::Pointer for Shared<'_, T> {
1664
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1665
+ fmt::Pointer::fmt(&(unsafe { self.deref() as *const _ }), f)
1666
+ }
1667
+ }
1668
+
1669
+ impl<T: ?Sized + Pointable> Default for Shared<'_, T> {
1670
+ fn default() -> Self {
1671
+ Shared::null()
1672
+ }
1673
+ }
1674
+
1675
+ #[cfg(all(test, not(crossbeam_loom)))]
1676
+ mod tests {
1677
+ use super::{Owned, Shared};
1678
+ use std::mem::MaybeUninit;
1679
+
1680
+ #[test]
1681
+ fn valid_tag_i8() {
1682
+ Shared::<i8>::null().with_tag(0);
1683
+ }
1684
+
1685
+ #[test]
1686
+ fn valid_tag_i64() {
1687
+ Shared::<i64>::null().with_tag(7);
1688
+ }
1689
+
1690
+ #[test]
1691
+ fn const_atomic_null() {
1692
+ use super::Atomic;
1693
+ static _U: Atomic<u8> = Atomic::<u8>::null();
1694
+ }
1695
+
1696
+ #[test]
1697
+ fn array_init() {
1698
+ let owned = Owned::<[MaybeUninit<usize>]>::init(10);
1699
+ let arr: &[MaybeUninit<usize>] = &owned;
1700
+ assert_eq!(arr.len(), 10);
1701
+ }
1702
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/collector.rs ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// Epoch-based garbage collector.
2
+ ///
3
+ /// # Examples
4
+ ///
5
+ /// ```
6
+ /// use crossbeam_epoch::Collector;
7
+ ///
8
+ /// let collector = Collector::new();
9
+ ///
10
+ /// let handle = collector.register();
11
+ /// drop(collector); // `handle` still works after dropping `collector`
12
+ ///
13
+ /// handle.pin().flush();
14
+ /// ```
15
+ use core::fmt;
16
+
17
+ use crate::guard::Guard;
18
+ use crate::internal::{Global, Local};
19
+ use crate::primitive::sync::Arc;
20
+
21
+ /// An epoch-based garbage collector.
22
+ pub struct Collector {
23
+ pub(crate) global: Arc<Global>,
24
+ }
25
+
26
+ unsafe impl Send for Collector {}
27
+ unsafe impl Sync for Collector {}
28
+
29
+ impl Default for Collector {
30
+ fn default() -> Self {
31
+ Self {
32
+ global: Arc::new(Global::new()),
33
+ }
34
+ }
35
+ }
36
+
37
+ impl Collector {
38
+ /// Creates a new collector.
39
+ pub fn new() -> Self {
40
+ Self::default()
41
+ }
42
+
43
+ /// Registers a new handle for the collector.
44
+ pub fn register(&self) -> LocalHandle {
45
+ Local::register(self)
46
+ }
47
+ }
48
+
49
+ impl Clone for Collector {
50
+ /// Creates another reference to the same garbage collector.
51
+ fn clone(&self) -> Self {
52
+ Collector {
53
+ global: self.global.clone(),
54
+ }
55
+ }
56
+ }
57
+
58
+ impl fmt::Debug for Collector {
59
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60
+ f.pad("Collector { .. }")
61
+ }
62
+ }
63
+
64
+ impl PartialEq for Collector {
65
+ /// Checks if both handles point to the same collector.
66
+ fn eq(&self, rhs: &Collector) -> bool {
67
+ Arc::ptr_eq(&self.global, &rhs.global)
68
+ }
69
+ }
70
+ impl Eq for Collector {}
71
+
72
+ /// A handle to a garbage collector.
73
+ pub struct LocalHandle {
74
+ pub(crate) local: *const Local,
75
+ }
76
+
77
+ impl LocalHandle {
78
+ /// Pins the handle.
79
+ #[inline]
80
+ pub fn pin(&self) -> Guard {
81
+ unsafe { (*self.local).pin() }
82
+ }
83
+
84
+ /// Returns `true` if the handle is pinned.
85
+ #[inline]
86
+ pub fn is_pinned(&self) -> bool {
87
+ unsafe { (*self.local).is_pinned() }
88
+ }
89
+
90
+ /// Returns the `Collector` associated with this handle.
91
+ #[inline]
92
+ pub fn collector(&self) -> &Collector {
93
+ unsafe { (*self.local).collector() }
94
+ }
95
+ }
96
+
97
+ impl Drop for LocalHandle {
98
+ #[inline]
99
+ fn drop(&mut self) {
100
+ unsafe {
101
+ Local::release_handle(&*self.local);
102
+ }
103
+ }
104
+ }
105
+
106
+ impl fmt::Debug for LocalHandle {
107
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108
+ f.pad("LocalHandle { .. }")
109
+ }
110
+ }
111
+
112
+ #[cfg(all(test, not(crossbeam_loom)))]
113
+ mod tests {
114
+ use std::mem::ManuallyDrop;
115
+ use std::sync::atomic::{AtomicUsize, Ordering};
116
+
117
+ use crossbeam_utils::thread;
118
+
119
+ use crate::{Collector, Owned};
120
+
121
+ const NUM_THREADS: usize = 8;
122
+
123
+ #[test]
124
+ fn pin_reentrant() {
125
+ let collector = Collector::new();
126
+ let handle = collector.register();
127
+ drop(collector);
128
+
129
+ assert!(!handle.is_pinned());
130
+ {
131
+ let _guard = &handle.pin();
132
+ assert!(handle.is_pinned());
133
+ {
134
+ let _guard = &handle.pin();
135
+ assert!(handle.is_pinned());
136
+ }
137
+ assert!(handle.is_pinned());
138
+ }
139
+ assert!(!handle.is_pinned());
140
+ }
141
+
142
+ #[test]
143
+ fn flush_local_bag() {
144
+ let collector = Collector::new();
145
+ let handle = collector.register();
146
+ drop(collector);
147
+
148
+ for _ in 0..100 {
149
+ let guard = &handle.pin();
150
+ unsafe {
151
+ let a = Owned::new(7).into_shared(guard);
152
+ guard.defer_destroy(a);
153
+
154
+ assert!(!(*guard.local).bag.with(|b| (*b).is_empty()));
155
+
156
+ while !(*guard.local).bag.with(|b| (*b).is_empty()) {
157
+ guard.flush();
158
+ }
159
+ }
160
+ }
161
+ }
162
+
163
+ #[test]
164
+ fn garbage_buffering() {
165
+ let collector = Collector::new();
166
+ let handle = collector.register();
167
+ drop(collector);
168
+
169
+ let guard = &handle.pin();
170
+ unsafe {
171
+ for _ in 0..10 {
172
+ let a = Owned::new(7).into_shared(guard);
173
+ guard.defer_destroy(a);
174
+ }
175
+ assert!(!(*guard.local).bag.with(|b| (*b).is_empty()));
176
+ }
177
+ }
178
+
179
+ #[test]
180
+ fn pin_holds_advance() {
181
+ #[cfg(miri)]
182
+ const N: usize = 500;
183
+ #[cfg(not(miri))]
184
+ const N: usize = 500_000;
185
+
186
+ let collector = Collector::new();
187
+
188
+ thread::scope(|scope| {
189
+ for _ in 0..NUM_THREADS {
190
+ scope.spawn(|_| {
191
+ let handle = collector.register();
192
+ for _ in 0..N {
193
+ let guard = &handle.pin();
194
+
195
+ let before = collector.global.epoch.load(Ordering::Relaxed);
196
+ collector.global.collect(guard);
197
+ let after = collector.global.epoch.load(Ordering::Relaxed);
198
+
199
+ assert!(after.wrapping_sub(before) <= 2);
200
+ }
201
+ });
202
+ }
203
+ })
204
+ .unwrap();
205
+ }
206
+
207
+ #[cfg(not(crossbeam_sanitize))] // TODO: assertions failed due to `cfg(crossbeam_sanitize)` reduce `internal::MAX_OBJECTS`
208
+ #[test]
209
+ fn incremental() {
210
+ #[cfg(miri)]
211
+ const COUNT: usize = 500;
212
+ #[cfg(not(miri))]
213
+ const COUNT: usize = 100_000;
214
+ static DESTROYS: AtomicUsize = AtomicUsize::new(0);
215
+
216
+ let collector = Collector::new();
217
+ let handle = collector.register();
218
+
219
+ unsafe {
220
+ let guard = &handle.pin();
221
+ for _ in 0..COUNT {
222
+ let a = Owned::new(7i32).into_shared(guard);
223
+ guard.defer_unchecked(move || {
224
+ drop(a.into_owned());
225
+ DESTROYS.fetch_add(1, Ordering::Relaxed);
226
+ });
227
+ }
228
+ guard.flush();
229
+ }
230
+
231
+ let mut last = 0;
232
+
233
+ while last < COUNT {
234
+ let curr = DESTROYS.load(Ordering::Relaxed);
235
+ assert!(curr - last <= 1024);
236
+ last = curr;
237
+
238
+ let guard = &handle.pin();
239
+ collector.global.collect(guard);
240
+ }
241
+ assert!(DESTROYS.load(Ordering::Relaxed) == COUNT);
242
+ }
243
+
244
+ #[test]
245
+ fn buffering() {
246
+ const COUNT: usize = 10;
247
+ #[cfg(miri)]
248
+ const N: usize = 500;
249
+ #[cfg(not(miri))]
250
+ const N: usize = 100_000;
251
+ static DESTROYS: AtomicUsize = AtomicUsize::new(0);
252
+
253
+ let collector = Collector::new();
254
+ let handle = collector.register();
255
+
256
+ unsafe {
257
+ let guard = &handle.pin();
258
+ for _ in 0..COUNT {
259
+ let a = Owned::new(7i32).into_shared(guard);
260
+ guard.defer_unchecked(move || {
261
+ drop(a.into_owned());
262
+ DESTROYS.fetch_add(1, Ordering::Relaxed);
263
+ });
264
+ }
265
+ }
266
+
267
+ for _ in 0..N {
268
+ collector.global.collect(&handle.pin());
269
+ }
270
+ assert!(DESTROYS.load(Ordering::Relaxed) < COUNT);
271
+
272
+ handle.pin().flush();
273
+
274
+ while DESTROYS.load(Ordering::Relaxed) < COUNT {
275
+ let guard = &handle.pin();
276
+ collector.global.collect(guard);
277
+ }
278
+ assert_eq!(DESTROYS.load(Ordering::Relaxed), COUNT);
279
+ }
280
+
281
+ #[test]
282
+ fn count_drops() {
283
+ #[cfg(miri)]
284
+ const COUNT: usize = 500;
285
+ #[cfg(not(miri))]
286
+ const COUNT: usize = 100_000;
287
+ static DROPS: AtomicUsize = AtomicUsize::new(0);
288
+
289
+ struct Elem(#[allow(dead_code)] i32);
290
+
291
+ impl Drop for Elem {
292
+ fn drop(&mut self) {
293
+ DROPS.fetch_add(1, Ordering::Relaxed);
294
+ }
295
+ }
296
+
297
+ let collector = Collector::new();
298
+ let handle = collector.register();
299
+
300
+ unsafe {
301
+ let guard = &handle.pin();
302
+
303
+ for _ in 0..COUNT {
304
+ let a = Owned::new(Elem(7i32)).into_shared(guard);
305
+ guard.defer_destroy(a);
306
+ }
307
+ guard.flush();
308
+ }
309
+
310
+ while DROPS.load(Ordering::Relaxed) < COUNT {
311
+ let guard = &handle.pin();
312
+ collector.global.collect(guard);
313
+ }
314
+ assert_eq!(DROPS.load(Ordering::Relaxed), COUNT);
315
+ }
316
+
317
+ #[test]
318
+ fn count_destroy() {
319
+ #[cfg(miri)]
320
+ const COUNT: usize = 500;
321
+ #[cfg(not(miri))]
322
+ const COUNT: usize = 100_000;
323
+ static DESTROYS: AtomicUsize = AtomicUsize::new(0);
324
+
325
+ let collector = Collector::new();
326
+ let handle = collector.register();
327
+
328
+ unsafe {
329
+ let guard = &handle.pin();
330
+
331
+ for _ in 0..COUNT {
332
+ let a = Owned::new(7i32).into_shared(guard);
333
+ guard.defer_unchecked(move || {
334
+ drop(a.into_owned());
335
+ DESTROYS.fetch_add(1, Ordering::Relaxed);
336
+ });
337
+ }
338
+ guard.flush();
339
+ }
340
+
341
+ while DESTROYS.load(Ordering::Relaxed) < COUNT {
342
+ let guard = &handle.pin();
343
+ collector.global.collect(guard);
344
+ }
345
+ assert_eq!(DESTROYS.load(Ordering::Relaxed), COUNT);
346
+ }
347
+
348
+ #[test]
349
+ fn drop_array() {
350
+ const COUNT: usize = 700;
351
+ static DROPS: AtomicUsize = AtomicUsize::new(0);
352
+
353
+ struct Elem(#[allow(dead_code)] i32);
354
+
355
+ impl Drop for Elem {
356
+ fn drop(&mut self) {
357
+ DROPS.fetch_add(1, Ordering::Relaxed);
358
+ }
359
+ }
360
+
361
+ let collector = Collector::new();
362
+ let handle = collector.register();
363
+
364
+ let mut guard = handle.pin();
365
+
366
+ let mut v = Vec::with_capacity(COUNT);
367
+ for i in 0..COUNT {
368
+ v.push(Elem(i as i32));
369
+ }
370
+
371
+ {
372
+ let a = Owned::new(v).into_shared(&guard);
373
+ unsafe {
374
+ guard.defer_destroy(a);
375
+ }
376
+ guard.flush();
377
+ }
378
+
379
+ while DROPS.load(Ordering::Relaxed) < COUNT {
380
+ guard.repin();
381
+ collector.global.collect(&guard);
382
+ }
383
+ assert_eq!(DROPS.load(Ordering::Relaxed), COUNT);
384
+ }
385
+
386
+ #[test]
387
+ fn destroy_array() {
388
+ #[cfg(miri)]
389
+ const COUNT: usize = 500;
390
+ #[cfg(not(miri))]
391
+ const COUNT: usize = 100_000;
392
+ static DESTROYS: AtomicUsize = AtomicUsize::new(0);
393
+
394
+ let collector = Collector::new();
395
+ let handle = collector.register();
396
+
397
+ unsafe {
398
+ let guard = &handle.pin();
399
+
400
+ let mut v = Vec::with_capacity(COUNT);
401
+ for i in 0..COUNT {
402
+ v.push(i as i32);
403
+ }
404
+
405
+ let len = v.len();
406
+ let cap = v.capacity();
407
+ let ptr = ManuallyDrop::new(v).as_mut_ptr();
408
+ guard.defer_unchecked(move || {
409
+ drop(Vec::from_raw_parts(ptr, len, cap));
410
+ DESTROYS.fetch_add(len, Ordering::Relaxed);
411
+ });
412
+ guard.flush();
413
+ }
414
+
415
+ while DESTROYS.load(Ordering::Relaxed) < COUNT {
416
+ let guard = &handle.pin();
417
+ collector.global.collect(guard);
418
+ }
419
+ assert_eq!(DESTROYS.load(Ordering::Relaxed), COUNT);
420
+ }
421
+
422
+ #[test]
423
+ fn stress() {
424
+ const THREADS: usize = 8;
425
+ #[cfg(miri)]
426
+ const COUNT: usize = 500;
427
+ #[cfg(not(miri))]
428
+ const COUNT: usize = 100_000;
429
+ static DROPS: AtomicUsize = AtomicUsize::new(0);
430
+
431
+ struct Elem(#[allow(dead_code)] i32);
432
+
433
+ impl Drop for Elem {
434
+ fn drop(&mut self) {
435
+ DROPS.fetch_add(1, Ordering::Relaxed);
436
+ }
437
+ }
438
+
439
+ let collector = Collector::new();
440
+
441
+ thread::scope(|scope| {
442
+ for _ in 0..THREADS {
443
+ scope.spawn(|_| {
444
+ let handle = collector.register();
445
+ for _ in 0..COUNT {
446
+ let guard = &handle.pin();
447
+ unsafe {
448
+ let a = Owned::new(Elem(7i32)).into_shared(guard);
449
+ guard.defer_destroy(a);
450
+ }
451
+ }
452
+ });
453
+ }
454
+ })
455
+ .unwrap();
456
+
457
+ let handle = collector.register();
458
+ while DROPS.load(Ordering::Relaxed) < COUNT * THREADS {
459
+ let guard = &handle.pin();
460
+ collector.global.collect(guard);
461
+ }
462
+ assert_eq!(DROPS.load(Ordering::Relaxed), COUNT * THREADS);
463
+ }
464
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/default.rs ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! The default garbage collector.
2
+ //!
3
+ //! For each thread, a participant is lazily initialized on its first use, when the current thread
4
+ //! is registered in the default collector. If initialized, the thread's participant will get
5
+ //! destructed on thread exit, which in turn unregisters the thread.
6
+
7
+ use crate::collector::{Collector, LocalHandle};
8
+ use crate::guard::Guard;
9
+ use crate::primitive::thread_local;
10
+ #[cfg(not(crossbeam_loom))]
11
+ use crate::sync::once_lock::OnceLock;
12
+
13
+ fn collector() -> &'static Collector {
14
+ #[cfg(not(crossbeam_loom))]
15
+ {
16
+ /// The global data for the default garbage collector.
17
+ static COLLECTOR: OnceLock<Collector> = OnceLock::new();
18
+ COLLECTOR.get_or_init(Collector::new)
19
+ }
20
+ // FIXME: loom does not currently provide the equivalent of Lazy:
21
+ // https://github.com/tokio-rs/loom/issues/263
22
+ #[cfg(crossbeam_loom)]
23
+ {
24
+ loom::lazy_static! {
25
+ /// The global data for the default garbage collector.
26
+ static ref COLLECTOR: Collector = Collector::new();
27
+ }
28
+ &COLLECTOR
29
+ }
30
+ }
31
+
32
+ thread_local! {
33
+ /// The per-thread participant for the default garbage collector.
34
+ static HANDLE: LocalHandle = collector().register();
35
+ }
36
+
37
+ /// Pins the current thread.
38
+ #[inline]
39
+ pub fn pin() -> Guard {
40
+ with_handle(|handle| handle.pin())
41
+ }
42
+
43
+ /// Returns `true` if the current thread is pinned.
44
+ #[inline]
45
+ pub fn is_pinned() -> bool {
46
+ with_handle(|handle| handle.is_pinned())
47
+ }
48
+
49
+ /// Returns the default global collector.
50
+ pub fn default_collector() -> &'static Collector {
51
+ collector()
52
+ }
53
+
54
+ #[inline]
55
+ fn with_handle<F, R>(mut f: F) -> R
56
+ where
57
+ F: FnMut(&LocalHandle) -> R,
58
+ {
59
+ HANDLE
60
+ .try_with(|h| f(h))
61
+ .unwrap_or_else(|_| f(&collector().register()))
62
+ }
63
+
64
+ #[cfg(all(test, not(crossbeam_loom)))]
65
+ mod tests {
66
+ use crossbeam_utils::thread;
67
+
68
+ #[test]
69
+ fn pin_while_exiting() {
70
+ struct Foo;
71
+
72
+ impl Drop for Foo {
73
+ fn drop(&mut self) {
74
+ // Pin after `HANDLE` has been dropped. This must not panic.
75
+ super::pin();
76
+ }
77
+ }
78
+
79
+ thread_local! {
80
+ static FOO: Foo = const { Foo };
81
+ }
82
+
83
+ thread::scope(|scope| {
84
+ scope.spawn(|_| {
85
+ // Initialize `FOO` and then `HANDLE`.
86
+ FOO.with(|_| ());
87
+ super::pin();
88
+ // At thread exit, `HANDLE` gets dropped first and `FOO` second.
89
+ });
90
+ })
91
+ .unwrap();
92
+ }
93
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/deferred.rs ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use alloc::boxed::Box;
2
+ use core::fmt;
3
+ use core::marker::PhantomData;
4
+ use core::mem::{self, MaybeUninit};
5
+ use core::ptr;
6
+
7
+ /// Number of words a piece of `Data` can hold.
8
+ ///
9
+ /// Three words should be enough for the majority of cases. For example, you can fit inside it the
10
+ /// function pointer together with a fat pointer representing an object that needs to be destroyed.
11
+ const DATA_WORDS: usize = 3;
12
+
13
+ /// Some space to keep a `FnOnce()` object on the stack.
14
+ type Data = [usize; DATA_WORDS];
15
+
16
+ /// A `FnOnce()` that is stored inline if small, or otherwise boxed on the heap.
17
+ ///
18
+ /// This is a handy way of keeping an unsized `FnOnce()` within a sized structure.
19
+ pub(crate) struct Deferred {
20
+ call: unsafe fn(*mut u8),
21
+ data: MaybeUninit<Data>,
22
+ _marker: PhantomData<*mut ()>, // !Send + !Sync
23
+ }
24
+
25
+ impl fmt::Debug for Deferred {
26
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
27
+ f.pad("Deferred { .. }")
28
+ }
29
+ }
30
+
31
+ impl Deferred {
32
+ pub(crate) const NO_OP: Self = {
33
+ fn no_op_call(_raw: *mut u8) {}
34
+ Self {
35
+ call: no_op_call,
36
+ data: MaybeUninit::uninit(),
37
+ _marker: PhantomData,
38
+ }
39
+ };
40
+
41
+ /// Constructs a new `Deferred` from a `FnOnce()`.
42
+ pub(crate) fn new<F: FnOnce()>(f: F) -> Self {
43
+ let size = mem::size_of::<F>();
44
+ let align = mem::align_of::<F>();
45
+
46
+ unsafe {
47
+ if size <= mem::size_of::<Data>() && align <= mem::align_of::<Data>() {
48
+ let mut data = MaybeUninit::<Data>::uninit();
49
+ ptr::write(data.as_mut_ptr().cast::<F>(), f);
50
+
51
+ unsafe fn call<F: FnOnce()>(raw: *mut u8) {
52
+ let f: F = ptr::read(raw.cast::<F>());
53
+ f();
54
+ }
55
+
56
+ Deferred {
57
+ call: call::<F>,
58
+ data,
59
+ _marker: PhantomData,
60
+ }
61
+ } else {
62
+ let b: Box<F> = Box::new(f);
63
+ let mut data = MaybeUninit::<Data>::uninit();
64
+ ptr::write(data.as_mut_ptr().cast::<Box<F>>(), b);
65
+
66
+ unsafe fn call<F: FnOnce()>(raw: *mut u8) {
67
+ // It's safe to cast `raw` from `*mut u8` to `*mut Box<F>`, because `raw` is
68
+ // originally derived from `*mut Box<F>`.
69
+ let b: Box<F> = ptr::read(raw.cast::<Box<F>>());
70
+ (*b)();
71
+ }
72
+
73
+ Deferred {
74
+ call: call::<F>,
75
+ data,
76
+ _marker: PhantomData,
77
+ }
78
+ }
79
+ }
80
+ }
81
+
82
+ /// Calls the function.
83
+ #[inline]
84
+ pub(crate) fn call(mut self) {
85
+ let call = self.call;
86
+ unsafe { call(self.data.as_mut_ptr().cast::<u8>()) };
87
+ }
88
+ }
89
+
90
+ #[cfg(all(test, not(crossbeam_loom)))]
91
+ mod tests {
92
+ use super::Deferred;
93
+ use std::cell::Cell;
94
+ use std::convert::identity;
95
+
96
+ #[test]
97
+ fn on_stack() {
98
+ let fired = &Cell::new(false);
99
+ let a = [0usize; 1];
100
+
101
+ let d = Deferred::new(move || {
102
+ let _ = identity(a);
103
+ fired.set(true);
104
+ });
105
+
106
+ assert!(!fired.get());
107
+ d.call();
108
+ assert!(fired.get());
109
+ }
110
+
111
+ #[test]
112
+ fn on_heap() {
113
+ let fired = &Cell::new(false);
114
+ let a = [0usize; 10];
115
+
116
+ let d = Deferred::new(move || {
117
+ let _ = identity(a);
118
+ fired.set(true);
119
+ });
120
+
121
+ assert!(!fired.get());
122
+ d.call();
123
+ assert!(fired.get());
124
+ }
125
+
126
+ #[test]
127
+ fn string() {
128
+ let a = "hello".to_string();
129
+ let d = Deferred::new(move || assert_eq!(a, "hello"));
130
+ d.call();
131
+ }
132
+
133
+ #[test]
134
+ fn boxed_slice_i32() {
135
+ let a: Box<[i32]> = vec![2, 3, 5, 7].into_boxed_slice();
136
+ let d = Deferred::new(move || assert_eq!(*a, [2, 3, 5, 7]));
137
+ d.call();
138
+ }
139
+
140
+ #[test]
141
+ fn long_slice_usize() {
142
+ let a: [usize; 5] = [2, 3, 5, 7, 11];
143
+ let d = Deferred::new(move || assert_eq!(a, [2, 3, 5, 7, 11]));
144
+ d.call();
145
+ }
146
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/epoch.rs ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! The global epoch
2
+ //!
3
+ //! The last bit in this number is unused and is always zero. Every so often the global epoch is
4
+ //! incremented, i.e. we say it "advances". A pinned participant may advance the global epoch only
5
+ //! if all currently pinned participants have been pinned in the current epoch.
6
+ //!
7
+ //! If an object became garbage in some epoch, then we can be sure that after two advancements no
8
+ //! participant will hold a reference to it. That is the crux of safe memory reclamation.
9
+
10
+ use crate::primitive::sync::atomic::{AtomicUsize, Ordering};
11
+
12
+ /// An epoch that can be marked as pinned or unpinned.
13
+ ///
14
+ /// Internally, the epoch is represented as an integer that wraps around at some unspecified point
15
+ /// and a flag that represents whether it is pinned or unpinned.
16
+ #[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
17
+ pub(crate) struct Epoch {
18
+ /// The least significant bit is set if pinned. The rest of the bits hold the epoch.
19
+ data: usize,
20
+ }
21
+
22
+ impl Epoch {
23
+ /// Returns the starting epoch in unpinned state.
24
+ #[inline]
25
+ pub(crate) fn starting() -> Self {
26
+ Self::default()
27
+ }
28
+
29
+ /// Returns the number of epochs `self` is ahead of `rhs`.
30
+ ///
31
+ /// Internally, epochs are represented as numbers in the range `(isize::MIN / 2) .. (isize::MAX
32
+ /// / 2)`, so the returned distance will be in the same interval.
33
+ pub(crate) fn wrapping_sub(self, rhs: Self) -> isize {
34
+ // The result is the same with `(self.data & !1).wrapping_sub(rhs.data & !1) as isize >> 1`,
35
+ // because the possible difference of LSB in `(self.data & !1).wrapping_sub(rhs.data & !1)`
36
+ // will be ignored in the shift operation.
37
+ self.data.wrapping_sub(rhs.data & !1) as isize >> 1
38
+ }
39
+
40
+ /// Returns `true` if the epoch is marked as pinned.
41
+ #[inline]
42
+ pub(crate) fn is_pinned(self) -> bool {
43
+ (self.data & 1) == 1
44
+ }
45
+
46
+ /// Returns the same epoch, but marked as pinned.
47
+ #[inline]
48
+ pub(crate) fn pinned(self) -> Epoch {
49
+ Epoch {
50
+ data: self.data | 1,
51
+ }
52
+ }
53
+
54
+ /// Returns the same epoch, but marked as unpinned.
55
+ #[inline]
56
+ pub(crate) fn unpinned(self) -> Epoch {
57
+ Epoch {
58
+ data: self.data & !1,
59
+ }
60
+ }
61
+
62
+ /// Returns the successor epoch.
63
+ ///
64
+ /// The returned epoch will be marked as pinned only if the previous one was as well.
65
+ #[inline]
66
+ pub(crate) fn successor(self) -> Epoch {
67
+ Epoch {
68
+ data: self.data.wrapping_add(2),
69
+ }
70
+ }
71
+ }
72
+
73
+ /// An atomic value that holds an `Epoch`.
74
+ #[derive(Default, Debug)]
75
+ pub(crate) struct AtomicEpoch {
76
+ /// Since `Epoch` is just a wrapper around `usize`, an `AtomicEpoch` is similarly represented
77
+ /// using an `AtomicUsize`.
78
+ data: AtomicUsize,
79
+ }
80
+
81
+ impl AtomicEpoch {
82
+ /// Creates a new atomic epoch.
83
+ #[inline]
84
+ pub(crate) fn new(epoch: Epoch) -> Self {
85
+ let data = AtomicUsize::new(epoch.data);
86
+ AtomicEpoch { data }
87
+ }
88
+
89
+ /// Loads a value from the atomic epoch.
90
+ #[inline]
91
+ pub(crate) fn load(&self, ord: Ordering) -> Epoch {
92
+ Epoch {
93
+ data: self.data.load(ord),
94
+ }
95
+ }
96
+
97
+ /// Stores a value into the atomic epoch.
98
+ #[inline]
99
+ pub(crate) fn store(&self, epoch: Epoch, ord: Ordering) {
100
+ self.data.store(epoch.data, ord);
101
+ }
102
+
103
+ /// Stores a value into the atomic epoch if the current value is the same as `current`.
104
+ ///
105
+ /// The return value is a result indicating whether the new value was written and containing
106
+ /// the previous value. On success this value is guaranteed to be equal to `current`.
107
+ ///
108
+ /// This method takes two `Ordering` arguments to describe the memory
109
+ /// ordering of this operation. `success` describes the required ordering for the
110
+ /// read-modify-write operation that takes place if the comparison with `current` succeeds.
111
+ /// `failure` describes the required ordering for the load operation that takes place when
112
+ /// the comparison fails. Using `Acquire` as success ordering makes the store part
113
+ /// of this operation `Relaxed`, and using `Release` makes the successful load
114
+ /// `Relaxed`. The failure ordering can only be `SeqCst`, `Acquire` or `Relaxed`
115
+ /// and must be equivalent to or weaker than the success ordering.
116
+ #[inline]
117
+ pub(crate) fn compare_exchange(
118
+ &self,
119
+ current: Epoch,
120
+ new: Epoch,
121
+ success: Ordering,
122
+ failure: Ordering,
123
+ ) -> Result<Epoch, Epoch> {
124
+ match self
125
+ .data
126
+ .compare_exchange(current.data, new.data, success, failure)
127
+ {
128
+ Ok(data) => Ok(Epoch { data }),
129
+ Err(data) => Err(Epoch { data }),
130
+ }
131
+ }
132
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/guard.rs ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use core::fmt;
2
+ use core::mem;
3
+
4
+ use crate::atomic::Shared;
5
+ use crate::collector::Collector;
6
+ use crate::deferred::Deferred;
7
+ use crate::internal::Local;
8
+
9
+ /// A guard that keeps the current thread pinned.
10
+ ///
11
+ /// # Pinning
12
+ ///
13
+ /// The current thread is pinned by calling [`pin`], which returns a new guard:
14
+ ///
15
+ /// ```
16
+ /// use crossbeam_epoch as epoch;
17
+ ///
18
+ /// // It is often convenient to prefix a call to `pin` with a `&` in order to create a reference.
19
+ /// // This is not really necessary, but makes passing references to the guard a bit easier.
20
+ /// let guard = &epoch::pin();
21
+ /// ```
22
+ ///
23
+ /// When a guard gets dropped, the current thread is automatically unpinned.
24
+ ///
25
+ /// # Pointers on the stack
26
+ ///
27
+ /// Having a guard allows us to create pointers on the stack to heap-allocated objects.
28
+ /// For example:
29
+ ///
30
+ /// ```
31
+ /// use crossbeam_epoch::{self as epoch, Atomic};
32
+ /// use std::sync::atomic::Ordering::SeqCst;
33
+ ///
34
+ /// // Create a heap-allocated number.
35
+ /// let a = Atomic::new(777);
36
+ ///
37
+ /// // Pin the current thread.
38
+ /// let guard = &epoch::pin();
39
+ ///
40
+ /// // Load the heap-allocated object and create pointer `p` on the stack.
41
+ /// let p = a.load(SeqCst, guard);
42
+ ///
43
+ /// // Dereference the pointer and print the value:
44
+ /// if let Some(num) = unsafe { p.as_ref() } {
45
+ /// println!("The number is {}.", num);
46
+ /// }
47
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
48
+ /// ```
49
+ ///
50
+ /// # Multiple guards
51
+ ///
52
+ /// Pinning is reentrant and it is perfectly legal to create multiple guards. In that case, the
53
+ /// thread will actually be pinned only when the first guard is created and unpinned when the last
54
+ /// one is dropped:
55
+ ///
56
+ /// ```
57
+ /// use crossbeam_epoch as epoch;
58
+ ///
59
+ /// let guard1 = epoch::pin();
60
+ /// let guard2 = epoch::pin();
61
+ /// assert!(epoch::is_pinned());
62
+ /// drop(guard1);
63
+ /// assert!(epoch::is_pinned());
64
+ /// drop(guard2);
65
+ /// assert!(!epoch::is_pinned());
66
+ /// ```
67
+ ///
68
+ /// [`pin`]: super::pin
69
+ pub struct Guard {
70
+ pub(crate) local: *const Local,
71
+ }
72
+
73
+ impl Guard {
74
+ /// Stores a function so that it can be executed at some point after all currently pinned
75
+ /// threads get unpinned.
76
+ ///
77
+ /// This method first stores `f` into the thread-local (or handle-local) cache. If this cache
78
+ /// becomes full, some functions are moved into the global cache. At the same time, some
79
+ /// functions from both local and global caches may get executed in order to incrementally
80
+ /// clean up the caches as they fill up.
81
+ ///
82
+ /// There is no guarantee when exactly `f` will be executed. The only guarantee is that it
83
+ /// won't be executed until all currently pinned threads get unpinned. In theory, `f` might
84
+ /// never run, but the epoch-based garbage collection will make an effort to execute it
85
+ /// reasonably soon.
86
+ ///
87
+ /// If this method is called from an [`unprotected`] guard, the function will simply be
88
+ /// executed immediately.
89
+ pub fn defer<F, R>(&self, f: F)
90
+ where
91
+ F: FnOnce() -> R,
92
+ F: Send + 'static,
93
+ {
94
+ unsafe {
95
+ self.defer_unchecked(f);
96
+ }
97
+ }
98
+
99
+ /// Stores a function so that it can be executed at some point after all currently pinned
100
+ /// threads get unpinned.
101
+ ///
102
+ /// This method first stores `f` into the thread-local (or handle-local) cache. If this cache
103
+ /// becomes full, some functions are moved into the global cache. At the same time, some
104
+ /// functions from both local and global caches may get executed in order to incrementally
105
+ /// clean up the caches as they fill up.
106
+ ///
107
+ /// There is no guarantee when exactly `f` will be executed. The only guarantee is that it
108
+ /// won't be executed until all currently pinned threads get unpinned. In theory, `f` might
109
+ /// never run, but the epoch-based garbage collection will make an effort to execute it
110
+ /// reasonably soon.
111
+ ///
112
+ /// If this method is called from an [`unprotected`] guard, the function will simply be
113
+ /// executed immediately.
114
+ ///
115
+ /// # Safety
116
+ ///
117
+ /// The given function must not hold reference onto the stack. It is highly recommended that
118
+ /// the passed function is **always** marked with `move` in order to prevent accidental
119
+ /// borrows.
120
+ ///
121
+ /// ```
122
+ /// use crossbeam_epoch as epoch;
123
+ ///
124
+ /// let guard = &epoch::pin();
125
+ /// let message = "Hello!";
126
+ /// unsafe {
127
+ /// // ALWAYS use `move` when sending a closure into `defer_unchecked`.
128
+ /// guard.defer_unchecked(move || {
129
+ /// println!("{}", message);
130
+ /// });
131
+ /// }
132
+ /// ```
133
+ ///
134
+ /// Apart from that, keep in mind that another thread may execute `f`, so anything accessed by
135
+ /// the closure must be `Send`.
136
+ ///
137
+ /// We intentionally didn't require `F: Send`, because Rust's type systems usually cannot prove
138
+ /// `F: Send` for typical use cases. For example, consider the following code snippet, which
139
+ /// exemplifies the typical use case of deferring the deallocation of a shared reference:
140
+ ///
141
+ /// ```ignore
142
+ /// let shared = Owned::new(7i32).into_shared(guard);
143
+ /// guard.defer_unchecked(move || shared.into_owned()); // `Shared` is not `Send`!
144
+ /// ```
145
+ ///
146
+ /// While `Shared` is not `Send`, it's safe for another thread to call the deferred function,
147
+ /// because it's called only after the grace period and `shared` is no longer shared with other
148
+ /// threads. But we don't expect type systems to prove this.
149
+ ///
150
+ /// # Examples
151
+ ///
152
+ /// When a heap-allocated object in a data structure becomes unreachable, it has to be
153
+ /// deallocated. However, the current thread and other threads may be still holding references
154
+ /// on the stack to that same object. Therefore it cannot be deallocated before those references
155
+ /// get dropped. This method can defer deallocation until all those threads get unpinned and
156
+ /// consequently drop all their references on the stack.
157
+ ///
158
+ /// ```
159
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
160
+ /// use std::sync::atomic::Ordering::SeqCst;
161
+ ///
162
+ /// let a = Atomic::new("foo");
163
+ ///
164
+ /// // Now suppose that `a` is shared among multiple threads and concurrently
165
+ /// // accessed and modified...
166
+ ///
167
+ /// // Pin the current thread.
168
+ /// let guard = &epoch::pin();
169
+ ///
170
+ /// // Steal the object currently stored in `a` and swap it with another one.
171
+ /// let p = a.swap(Owned::new("bar").into_shared(guard), SeqCst, guard);
172
+ ///
173
+ /// if !p.is_null() {
174
+ /// // The object `p` is pointing to is now unreachable.
175
+ /// // Defer its deallocation until all currently pinned threads get unpinned.
176
+ /// unsafe {
177
+ /// // ALWAYS use `move` when sending a closure into `defer_unchecked`.
178
+ /// guard.defer_unchecked(move || {
179
+ /// println!("{} is now being deallocated.", p.deref());
180
+ /// // Now we have unique access to the object pointed to by `p` and can turn it
181
+ /// // into an `Owned`. Dropping the `Owned` will deallocate the object.
182
+ /// drop(p.into_owned());
183
+ /// });
184
+ /// }
185
+ /// }
186
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
187
+ /// ```
188
+ pub unsafe fn defer_unchecked<F, R>(&self, f: F)
189
+ where
190
+ F: FnOnce() -> R,
191
+ {
192
+ if let Some(local) = self.local.as_ref() {
193
+ local.defer(Deferred::new(move || drop(f())), self);
194
+ } else {
195
+ drop(f());
196
+ }
197
+ }
198
+
199
+ /// Stores a destructor for an object so that it can be deallocated and dropped at some point
200
+ /// after all currently pinned threads get unpinned.
201
+ ///
202
+ /// This method first stores the destructor into the thread-local (or handle-local) cache. If
203
+ /// this cache becomes full, some destructors are moved into the global cache. At the same
204
+ /// time, some destructors from both local and global caches may get executed in order to
205
+ /// incrementally clean up the caches as they fill up.
206
+ ///
207
+ /// There is no guarantee when exactly the destructor will be executed. The only guarantee is
208
+ /// that it won't be executed until all currently pinned threads get unpinned. In theory, the
209
+ /// destructor might never run, but the epoch-based garbage collection will make an effort to
210
+ /// execute it reasonably soon.
211
+ ///
212
+ /// If this method is called from an [`unprotected`] guard, the destructor will simply be
213
+ /// executed immediately.
214
+ ///
215
+ /// # Safety
216
+ ///
217
+ /// The object must not be reachable by other threads anymore, otherwise it might be still in
218
+ /// use when the destructor runs.
219
+ ///
220
+ /// Apart from that, keep in mind that another thread may execute the destructor, so the object
221
+ /// must be sendable to other threads.
222
+ ///
223
+ /// We intentionally didn't require `T: Send`, because Rust's type systems usually cannot prove
224
+ /// `T: Send` for typical use cases. For example, consider the following code snippet, which
225
+ /// exemplifies the typical use case of deferring the deallocation of a shared reference:
226
+ ///
227
+ /// ```ignore
228
+ /// let shared = Owned::new(7i32).into_shared(guard);
229
+ /// guard.defer_destroy(shared); // `Shared` is not `Send`!
230
+ /// ```
231
+ ///
232
+ /// While `Shared` is not `Send`, it's safe for another thread to call the destructor, because
233
+ /// it's called only after the grace period and `shared` is no longer shared with other
234
+ /// threads. But we don't expect type systems to prove this.
235
+ ///
236
+ /// # Examples
237
+ ///
238
+ /// When a heap-allocated object in a data structure becomes unreachable, it has to be
239
+ /// deallocated. However, the current thread and other threads may be still holding references
240
+ /// on the stack to that same object. Therefore it cannot be deallocated before those references
241
+ /// get dropped. This method can defer deallocation until all those threads get unpinned and
242
+ /// consequently drop all their references on the stack.
243
+ ///
244
+ /// ```
245
+ /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
246
+ /// use std::sync::atomic::Ordering::SeqCst;
247
+ ///
248
+ /// let a = Atomic::new("foo");
249
+ ///
250
+ /// // Now suppose that `a` is shared among multiple threads and concurrently
251
+ /// // accessed and modified...
252
+ ///
253
+ /// // Pin the current thread.
254
+ /// let guard = &epoch::pin();
255
+ ///
256
+ /// // Steal the object currently stored in `a` and swap it with another one.
257
+ /// let p = a.swap(Owned::new("bar").into_shared(guard), SeqCst, guard);
258
+ ///
259
+ /// if !p.is_null() {
260
+ /// // The object `p` is pointing to is now unreachable.
261
+ /// // Defer its deallocation until all currently pinned threads get unpinned.
262
+ /// unsafe {
263
+ /// guard.defer_destroy(p);
264
+ /// }
265
+ /// }
266
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
267
+ /// ```
268
+ pub unsafe fn defer_destroy<T>(&self, ptr: Shared<'_, T>) {
269
+ self.defer_unchecked(move || ptr.into_owned());
270
+ }
271
+
272
+ /// Clears up the thread-local cache of deferred functions by executing them or moving into the
273
+ /// global cache.
274
+ ///
275
+ /// Call this method after deferring execution of a function if you want to get it executed as
276
+ /// soon as possible. Flushing will make sure it is residing in in the global cache, so that
277
+ /// any thread has a chance of taking the function and executing it.
278
+ ///
279
+ /// If this method is called from an [`unprotected`] guard, it is a no-op (nothing happens).
280
+ ///
281
+ /// # Examples
282
+ ///
283
+ /// ```
284
+ /// use crossbeam_epoch as epoch;
285
+ ///
286
+ /// let guard = &epoch::pin();
287
+ /// guard.defer(move || {
288
+ /// println!("This better be printed as soon as possible!");
289
+ /// });
290
+ /// guard.flush();
291
+ /// ```
292
+ pub fn flush(&self) {
293
+ if let Some(local) = unsafe { self.local.as_ref() } {
294
+ local.flush(self);
295
+ }
296
+ }
297
+
298
+ /// Unpins and then immediately re-pins the thread.
299
+ ///
300
+ /// This method is useful when you don't want delay the advancement of the global epoch by
301
+ /// holding an old epoch. For safety, you should not maintain any guard-based reference across
302
+ /// the call (the latter is enforced by `&mut self`). The thread will only be repinned if this
303
+ /// is the only active guard for the current thread.
304
+ ///
305
+ /// If this method is called from an [`unprotected`] guard, then the call will be just no-op.
306
+ ///
307
+ /// # Examples
308
+ ///
309
+ /// ```
310
+ /// use crossbeam_epoch::{self as epoch, Atomic};
311
+ /// use std::sync::atomic::Ordering::SeqCst;
312
+ ///
313
+ /// let a = Atomic::new(777);
314
+ /// let mut guard = epoch::pin();
315
+ /// {
316
+ /// let p = a.load(SeqCst, &guard);
317
+ /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
318
+ /// }
319
+ /// guard.repin();
320
+ /// {
321
+ /// let p = a.load(SeqCst, &guard);
322
+ /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
323
+ /// }
324
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
325
+ /// ```
326
+ pub fn repin(&mut self) {
327
+ if let Some(local) = unsafe { self.local.as_ref() } {
328
+ local.repin();
329
+ }
330
+ }
331
+
332
+ /// Temporarily unpins the thread, executes the given function and then re-pins the thread.
333
+ ///
334
+ /// This method is useful when you need to perform a long-running operation (e.g. sleeping)
335
+ /// and don't need to maintain any guard-based reference across the call (the latter is enforced
336
+ /// by `&mut self`). The thread will only be unpinned if this is the only active guard for the
337
+ /// current thread.
338
+ ///
339
+ /// If this method is called from an [`unprotected`] guard, then the passed function is called
340
+ /// directly without unpinning the thread.
341
+ ///
342
+ /// # Examples
343
+ ///
344
+ /// ```
345
+ /// use crossbeam_epoch::{self as epoch, Atomic};
346
+ /// use std::sync::atomic::Ordering::SeqCst;
347
+ /// use std::thread;
348
+ /// use std::time::Duration;
349
+ ///
350
+ /// let a = Atomic::new(777);
351
+ /// let mut guard = epoch::pin();
352
+ /// {
353
+ /// let p = a.load(SeqCst, &guard);
354
+ /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
355
+ /// }
356
+ /// guard.repin_after(|| thread::sleep(Duration::from_millis(50)));
357
+ /// {
358
+ /// let p = a.load(SeqCst, &guard);
359
+ /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
360
+ /// }
361
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
362
+ /// ```
363
+ pub fn repin_after<F, R>(&mut self, f: F) -> R
364
+ where
365
+ F: FnOnce() -> R,
366
+ {
367
+ // Ensure the Guard is re-pinned even if the function panics
368
+ struct ScopeGuard(*const Local);
369
+ impl Drop for ScopeGuard {
370
+ fn drop(&mut self) {
371
+ if let Some(local) = unsafe { self.0.as_ref() } {
372
+ mem::forget(local.pin());
373
+ local.release_handle();
374
+ }
375
+ }
376
+ }
377
+
378
+ if let Some(local) = unsafe { self.local.as_ref() } {
379
+ // We need to acquire a handle here to ensure the Local doesn't
380
+ // disappear from under us.
381
+ local.acquire_handle();
382
+ local.unpin();
383
+ }
384
+
385
+ let _guard = ScopeGuard(self.local);
386
+
387
+ f()
388
+ }
389
+
390
+ /// Returns the `Collector` associated with this guard.
391
+ ///
392
+ /// This method is useful when you need to ensure that all guards used with
393
+ /// a data structure come from the same collector.
394
+ ///
395
+ /// If this method is called from an [`unprotected`] guard, then `None` is returned.
396
+ ///
397
+ /// # Examples
398
+ ///
399
+ /// ```
400
+ /// use crossbeam_epoch as epoch;
401
+ ///
402
+ /// let guard1 = epoch::pin();
403
+ /// let guard2 = epoch::pin();
404
+ /// assert!(guard1.collector() == guard2.collector());
405
+ /// ```
406
+ pub fn collector(&self) -> Option<&Collector> {
407
+ unsafe { self.local.as_ref().map(|local| local.collector()) }
408
+ }
409
+ }
410
+
411
+ impl Drop for Guard {
412
+ #[inline]
413
+ fn drop(&mut self) {
414
+ if let Some(local) = unsafe { self.local.as_ref() } {
415
+ local.unpin();
416
+ }
417
+ }
418
+ }
419
+
420
+ impl fmt::Debug for Guard {
421
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422
+ f.pad("Guard { .. }")
423
+ }
424
+ }
425
+
426
+ /// Returns a reference to a dummy guard that allows unprotected access to [`Atomic`]s.
427
+ ///
428
+ /// This guard should be used in special occasions only. Note that it doesn't actually keep any
429
+ /// thread pinned - it's just a fake guard that allows loading from [`Atomic`]s unsafely.
430
+ ///
431
+ /// Note that calling [`defer`] with a dummy guard will not defer the function - it will just
432
+ /// execute the function immediately.
433
+ ///
434
+ /// If necessary, it's possible to create more dummy guards by cloning: `unprotected().clone()`.
435
+ ///
436
+ /// # Safety
437
+ ///
438
+ /// Loading and dereferencing data from an [`Atomic`] using this guard is safe only if the
439
+ /// [`Atomic`] is not being concurrently modified by other threads.
440
+ ///
441
+ /// # Examples
442
+ ///
443
+ /// ```
444
+ /// use crossbeam_epoch::{self as epoch, Atomic};
445
+ /// use std::sync::atomic::Ordering::Relaxed;
446
+ ///
447
+ /// let a = Atomic::new(7);
448
+ ///
449
+ /// unsafe {
450
+ /// // Load `a` without pinning the current thread.
451
+ /// a.load(Relaxed, epoch::unprotected());
452
+ ///
453
+ /// // It's possible to create more dummy guards.
454
+ /// let dummy = epoch::unprotected();
455
+ ///
456
+ /// dummy.defer(move || {
457
+ /// println!("This gets executed immediately.");
458
+ /// });
459
+ ///
460
+ /// // Dropping `dummy` doesn't affect the current thread - it's just a noop.
461
+ /// }
462
+ /// # unsafe { drop(a.into_owned()); } // avoid leak
463
+ /// ```
464
+ ///
465
+ /// The most common use of this function is when constructing or destructing a data structure.
466
+ ///
467
+ /// For example, we can use a dummy guard in the destructor of a Treiber stack because at that
468
+ /// point no other thread could concurrently modify the [`Atomic`]s we are accessing.
469
+ ///
470
+ /// If we were to actually pin the current thread during destruction, that would just unnecessarily
471
+ /// delay garbage collection and incur some performance cost, so in cases like these `unprotected`
472
+ /// is very helpful.
473
+ ///
474
+ /// ```
475
+ /// use crossbeam_epoch::{self as epoch, Atomic};
476
+ /// use std::mem::ManuallyDrop;
477
+ /// use std::sync::atomic::Ordering::Relaxed;
478
+ ///
479
+ /// struct Stack<T> {
480
+ /// head: Atomic<Node<T>>,
481
+ /// }
482
+ ///
483
+ /// struct Node<T> {
484
+ /// data: ManuallyDrop<T>,
485
+ /// next: Atomic<Node<T>>,
486
+ /// }
487
+ ///
488
+ /// impl<T> Drop for Stack<T> {
489
+ /// fn drop(&mut self) {
490
+ /// unsafe {
491
+ /// // Unprotected load.
492
+ /// let mut node = self.head.load(Relaxed, epoch::unprotected());
493
+ ///
494
+ /// while let Some(n) = node.as_ref() {
495
+ /// // Unprotected load.
496
+ /// let next = n.next.load(Relaxed, epoch::unprotected());
497
+ ///
498
+ /// // Take ownership of the node, then drop its data and deallocate it.
499
+ /// let mut o = node.into_owned();
500
+ /// ManuallyDrop::drop(&mut o.data);
501
+ /// drop(o);
502
+ ///
503
+ /// node = next;
504
+ /// }
505
+ /// }
506
+ /// }
507
+ /// }
508
+ /// ```
509
+ ///
510
+ /// [`Atomic`]: super::Atomic
511
+ /// [`defer`]: Guard::defer
512
+ #[inline]
513
+ pub unsafe fn unprotected() -> &'static Guard {
514
+ // An unprotected guard is just a `Guard` with its field `local` set to null.
515
+ // We make a newtype over `Guard` because `Guard` isn't `Sync`, so can't be directly stored in
516
+ // a `static`
517
+ struct GuardWrapper(Guard);
518
+ unsafe impl Sync for GuardWrapper {}
519
+ static UNPROTECTED: GuardWrapper = GuardWrapper(Guard {
520
+ local: core::ptr::null(),
521
+ });
522
+ &UNPROTECTED.0
523
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/internal.rs ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! The global data and participant for garbage collection.
2
+ //!
3
+ //! # Registration
4
+ //!
5
+ //! In order to track all participants in one place, we need some form of participant
6
+ //! registration. When a participant is created, it is registered to a global lock-free
7
+ //! singly-linked list of registries; and when a participant is leaving, it is unregistered from the
8
+ //! list.
9
+ //!
10
+ //! # Pinning
11
+ //!
12
+ //! Every participant contains an integer that tells whether the participant is pinned and if so,
13
+ //! what was the global epoch at the time it was pinned. Participants also hold a pin counter that
14
+ //! aids in periodic global epoch advancement.
15
+ //!
16
+ //! When a participant is pinned, a `Guard` is returned as a witness that the participant is pinned.
17
+ //! Guards are necessary for performing atomic operations, and for freeing/dropping locations.
18
+ //!
19
+ //! # Thread-local bag
20
+ //!
21
+ //! Objects that get unlinked from concurrent data structures must be stashed away until the global
22
+ //! epoch sufficiently advances so that they become safe for destruction. Pointers to such objects
23
+ //! are pushed into a thread-local bag, and when it becomes full, the bag is marked with the current
24
+ //! global epoch and pushed into the global queue of bags. We store objects in thread-local storages
25
+ //! for amortizing the synchronization cost of pushing the garbages to a global queue.
26
+ //!
27
+ //! # Global queue
28
+ //!
29
+ //! Whenever a bag is pushed into a queue, the objects in some bags in the queue are collected and
30
+ //! destroyed along the way. This design reduces contention on data structures. The global queue
31
+ //! cannot be explicitly accessed: the only way to interact with it is by calling functions
32
+ //! `defer()` that adds an object to the thread-local bag, or `collect()` that manually triggers
33
+ //! garbage collection.
34
+ //!
35
+ //! Ideally each instance of concurrent data structure may have its own queue that gets fully
36
+ //! destroyed as soon as the data structure gets dropped.
37
+
38
+ use crate::primitive::cell::UnsafeCell;
39
+ use crate::primitive::sync::atomic::{self, Ordering};
40
+ use core::cell::Cell;
41
+ use core::mem::{self, ManuallyDrop};
42
+ use core::num::Wrapping;
43
+ use core::{fmt, ptr};
44
+
45
+ use crossbeam_utils::CachePadded;
46
+
47
+ use crate::atomic::{Owned, Shared};
48
+ use crate::collector::{Collector, LocalHandle};
49
+ use crate::deferred::Deferred;
50
+ use crate::epoch::{AtomicEpoch, Epoch};
51
+ use crate::guard::{unprotected, Guard};
52
+ use crate::sync::list::{Entry, IsElement, IterError, List};
53
+ use crate::sync::queue::Queue;
54
+
55
+ /// Maximum number of objects a bag can contain.
56
+ #[cfg(not(any(crossbeam_sanitize, miri)))]
57
+ const MAX_OBJECTS: usize = 64;
58
+ // Makes it more likely to trigger any potential data races.
59
+ #[cfg(any(crossbeam_sanitize, miri))]
60
+ const MAX_OBJECTS: usize = 4;
61
+
62
+ /// A bag of deferred functions.
63
+ pub(crate) struct Bag {
64
+ /// Stashed objects.
65
+ deferreds: [Deferred; MAX_OBJECTS],
66
+ len: usize,
67
+ }
68
+
69
+ /// `Bag::try_push()` requires that it is safe for another thread to execute the given functions.
70
+ unsafe impl Send for Bag {}
71
+
72
+ impl Bag {
73
+ /// Returns a new, empty bag.
74
+ pub(crate) fn new() -> Self {
75
+ Self::default()
76
+ }
77
+
78
+ /// Returns `true` if the bag is empty.
79
+ pub(crate) fn is_empty(&self) -> bool {
80
+ self.len == 0
81
+ }
82
+
83
+ /// Attempts to insert a deferred function into the bag.
84
+ ///
85
+ /// Returns `Ok(())` if successful, and `Err(deferred)` for the given `deferred` if the bag is
86
+ /// full.
87
+ ///
88
+ /// # Safety
89
+ ///
90
+ /// It should be safe for another thread to execute the given function.
91
+ pub(crate) unsafe fn try_push(&mut self, deferred: Deferred) -> Result<(), Deferred> {
92
+ if self.len < MAX_OBJECTS {
93
+ self.deferreds[self.len] = deferred;
94
+ self.len += 1;
95
+ Ok(())
96
+ } else {
97
+ Err(deferred)
98
+ }
99
+ }
100
+
101
+ /// Seals the bag with the given epoch.
102
+ fn seal(self, epoch: Epoch) -> SealedBag {
103
+ SealedBag { epoch, _bag: self }
104
+ }
105
+ }
106
+
107
+ impl Default for Bag {
108
+ fn default() -> Self {
109
+ Bag {
110
+ len: 0,
111
+ deferreds: [Deferred::NO_OP; MAX_OBJECTS],
112
+ }
113
+ }
114
+ }
115
+
116
+ impl Drop for Bag {
117
+ fn drop(&mut self) {
118
+ // Call all deferred functions.
119
+ for deferred in &mut self.deferreds[..self.len] {
120
+ let no_op = Deferred::NO_OP;
121
+ let owned_deferred = mem::replace(deferred, no_op);
122
+ owned_deferred.call();
123
+ }
124
+ }
125
+ }
126
+
127
+ // can't #[derive(Debug)] because Debug is not implemented for arrays 64 items long
128
+ impl fmt::Debug for Bag {
129
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130
+ f.debug_struct("Bag")
131
+ .field("deferreds", &&self.deferreds[..self.len])
132
+ .finish()
133
+ }
134
+ }
135
+
136
+ /// A pair of an epoch and a bag.
137
+ #[derive(Default, Debug)]
138
+ struct SealedBag {
139
+ epoch: Epoch,
140
+ _bag: Bag,
141
+ }
142
+
143
+ /// It is safe to share `SealedBag` because `is_expired` only inspects the epoch.
144
+ unsafe impl Sync for SealedBag {}
145
+
146
+ impl SealedBag {
147
+ /// Checks if it is safe to drop the bag w.r.t. the given global epoch.
148
+ fn is_expired(&self, global_epoch: Epoch) -> bool {
149
+ // A pinned participant can witness at most one epoch advancement. Therefore, any bag that
150
+ // is within one epoch of the current one cannot be destroyed yet.
151
+ global_epoch.wrapping_sub(self.epoch) >= 2
152
+ }
153
+ }
154
+
155
+ /// The global data for a garbage collector.
156
+ pub(crate) struct Global {
157
+ /// The intrusive linked list of `Local`s.
158
+ locals: List<Local>,
159
+
160
+ /// The global queue of bags of deferred functions.
161
+ queue: Queue<SealedBag>,
162
+
163
+ /// The global epoch.
164
+ pub(crate) epoch: CachePadded<AtomicEpoch>,
165
+ }
166
+
167
+ impl Global {
168
+ /// Number of bags to destroy.
169
+ const COLLECT_STEPS: usize = 8;
170
+
171
+ /// Creates a new global data for garbage collection.
172
+ #[inline]
173
+ pub(crate) fn new() -> Self {
174
+ Self {
175
+ locals: List::new(),
176
+ queue: Queue::new(),
177
+ epoch: CachePadded::new(AtomicEpoch::new(Epoch::starting())),
178
+ }
179
+ }
180
+
181
+ /// Pushes the bag into the global queue and replaces the bag with a new empty bag.
182
+ pub(crate) fn push_bag(&self, bag: &mut Bag, guard: &Guard) {
183
+ let bag = mem::replace(bag, Bag::new());
184
+
185
+ atomic::fence(Ordering::SeqCst);
186
+
187
+ let epoch = self.epoch.load(Ordering::Relaxed);
188
+ self.queue.push(bag.seal(epoch), guard);
189
+ }
190
+
191
+ /// Collects several bags from the global queue and executes deferred functions in them.
192
+ ///
193
+ /// Note: This may itself produce garbage and in turn allocate new bags.
194
+ ///
195
+ /// `pin()` rarely calls `collect()`, so we want the compiler to place that call on a cold
196
+ /// path. In other words, we want the compiler to optimize branching for the case when
197
+ /// `collect()` is not called.
198
+ #[cold]
199
+ pub(crate) fn collect(&self, guard: &Guard) {
200
+ let global_epoch = self.try_advance(guard);
201
+
202
+ let steps = if cfg!(crossbeam_sanitize) {
203
+ usize::max_value()
204
+ } else {
205
+ Self::COLLECT_STEPS
206
+ };
207
+
208
+ for _ in 0..steps {
209
+ match self.queue.try_pop_if(
210
+ &|sealed_bag: &SealedBag| sealed_bag.is_expired(global_epoch),
211
+ guard,
212
+ ) {
213
+ None => break,
214
+ Some(sealed_bag) => drop(sealed_bag),
215
+ }
216
+ }
217
+ }
218
+
219
+ /// Attempts to advance the global epoch.
220
+ ///
221
+ /// The global epoch can advance only if all currently pinned participants have been pinned in
222
+ /// the current epoch.
223
+ ///
224
+ /// Returns the current global epoch.
225
+ ///
226
+ /// `try_advance()` is annotated `#[cold]` because it is rarely called.
227
+ #[cold]
228
+ pub(crate) fn try_advance(&self, guard: &Guard) -> Epoch {
229
+ let global_epoch = self.epoch.load(Ordering::Relaxed);
230
+ atomic::fence(Ordering::SeqCst);
231
+
232
+ // TODO(stjepang): `Local`s are stored in a linked list because linked lists are fairly
233
+ // easy to implement in a lock-free manner. However, traversal can be slow due to cache
234
+ // misses and data dependencies. We should experiment with other data structures as well.
235
+ for local in self.locals.iter(guard) {
236
+ match local {
237
+ Err(IterError::Stalled) => {
238
+ // A concurrent thread stalled this iteration. That thread might also try to
239
+ // advance the epoch, in which case we leave the job to it. Otherwise, the
240
+ // epoch will not be advanced.
241
+ return global_epoch;
242
+ }
243
+ Ok(local) => {
244
+ let local_epoch = local.epoch.load(Ordering::Relaxed);
245
+
246
+ // If the participant was pinned in a different epoch, we cannot advance the
247
+ // global epoch just yet.
248
+ if local_epoch.is_pinned() && local_epoch.unpinned() != global_epoch {
249
+ return global_epoch;
250
+ }
251
+ }
252
+ }
253
+ }
254
+ atomic::fence(Ordering::Acquire);
255
+
256
+ // All pinned participants were pinned in the current global epoch.
257
+ // Now let's advance the global epoch...
258
+ //
259
+ // Note that if another thread already advanced it before us, this store will simply
260
+ // overwrite the global epoch with the same value. This is true because `try_advance` was
261
+ // called from a thread that was pinned in `global_epoch`, and the global epoch cannot be
262
+ // advanced two steps ahead of it.
263
+ let new_epoch = global_epoch.successor();
264
+ self.epoch.store(new_epoch, Ordering::Release);
265
+ new_epoch
266
+ }
267
+ }
268
+
269
+ /// Participant for garbage collection.
270
+ #[repr(C)] // Note: `entry` must be the first field
271
+ pub(crate) struct Local {
272
+ /// A node in the intrusive linked list of `Local`s.
273
+ entry: Entry,
274
+
275
+ /// A reference to the global data.
276
+ ///
277
+ /// When all guards and handles get dropped, this reference is destroyed.
278
+ collector: UnsafeCell<ManuallyDrop<Collector>>,
279
+
280
+ /// The local bag of deferred functions.
281
+ pub(crate) bag: UnsafeCell<Bag>,
282
+
283
+ /// The number of guards keeping this participant pinned.
284
+ guard_count: Cell<usize>,
285
+
286
+ /// The number of active handles.
287
+ handle_count: Cell<usize>,
288
+
289
+ /// Total number of pinnings performed.
290
+ ///
291
+ /// This is just an auxiliary counter that sometimes kicks off collection.
292
+ pin_count: Cell<Wrapping<usize>>,
293
+
294
+ /// The local epoch.
295
+ epoch: CachePadded<AtomicEpoch>,
296
+ }
297
+
298
+ // Make sure `Local` is less than or equal to 2048 bytes.
299
+ // https://github.com/crossbeam-rs/crossbeam/issues/551
300
+ #[cfg(not(any(crossbeam_sanitize, miri)))] // `crossbeam_sanitize` and `miri` reduce the size of `Local`
301
+ #[test]
302
+ fn local_size() {
303
+ // TODO: https://github.com/crossbeam-rs/crossbeam/issues/869
304
+ // assert!(
305
+ // core::mem::size_of::<Local>() <= 2048,
306
+ // "An allocation of `Local` should be <= 2048 bytes."
307
+ // );
308
+ }
309
+
310
+ impl Local {
311
+ /// Number of pinnings after which a participant will execute some deferred functions from the
312
+ /// global queue.
313
+ const PINNINGS_BETWEEN_COLLECT: usize = 128;
314
+
315
+ /// Registers a new `Local` in the provided `Global`.
316
+ pub(crate) fn register(collector: &Collector) -> LocalHandle {
317
+ unsafe {
318
+ // Since we dereference no pointers in this block, it is safe to use `unprotected`.
319
+
320
+ let local = Owned::new(Local {
321
+ entry: Entry::default(),
322
+ collector: UnsafeCell::new(ManuallyDrop::new(collector.clone())),
323
+ bag: UnsafeCell::new(Bag::new()),
324
+ guard_count: Cell::new(0),
325
+ handle_count: Cell::new(1),
326
+ pin_count: Cell::new(Wrapping(0)),
327
+ epoch: CachePadded::new(AtomicEpoch::new(Epoch::starting())),
328
+ })
329
+ .into_shared(unprotected());
330
+ collector.global.locals.insert(local, unprotected());
331
+ LocalHandle {
332
+ local: local.as_raw(),
333
+ }
334
+ }
335
+ }
336
+
337
+ /// Returns a reference to the `Global` in which this `Local` resides.
338
+ #[inline]
339
+ pub(crate) fn global(&self) -> &Global {
340
+ &self.collector().global
341
+ }
342
+
343
+ /// Returns a reference to the `Collector` in which this `Local` resides.
344
+ #[inline]
345
+ pub(crate) fn collector(&self) -> &Collector {
346
+ self.collector.with(|c| unsafe { &**c })
347
+ }
348
+
349
+ /// Returns `true` if the current participant is pinned.
350
+ #[inline]
351
+ pub(crate) fn is_pinned(&self) -> bool {
352
+ self.guard_count.get() > 0
353
+ }
354
+
355
+ /// Adds `deferred` to the thread-local bag.
356
+ ///
357
+ /// # Safety
358
+ ///
359
+ /// It should be safe for another thread to execute the given function.
360
+ pub(crate) unsafe fn defer(&self, mut deferred: Deferred, guard: &Guard) {
361
+ let bag = self.bag.with_mut(|b| &mut *b);
362
+
363
+ while let Err(d) = bag.try_push(deferred) {
364
+ self.global().push_bag(bag, guard);
365
+ deferred = d;
366
+ }
367
+ }
368
+
369
+ pub(crate) fn flush(&self, guard: &Guard) {
370
+ let bag = self.bag.with_mut(|b| unsafe { &mut *b });
371
+
372
+ if !bag.is_empty() {
373
+ self.global().push_bag(bag, guard);
374
+ }
375
+
376
+ self.global().collect(guard);
377
+ }
378
+
379
+ /// Pins the `Local`.
380
+ #[inline]
381
+ pub(crate) fn pin(&self) -> Guard {
382
+ let guard = Guard { local: self };
383
+
384
+ let guard_count = self.guard_count.get();
385
+ self.guard_count.set(guard_count.checked_add(1).unwrap());
386
+
387
+ if guard_count == 0 {
388
+ let global_epoch = self.global().epoch.load(Ordering::Relaxed);
389
+ let new_epoch = global_epoch.pinned();
390
+
391
+ // Now we must store `new_epoch` into `self.epoch` and execute a `SeqCst` fence.
392
+ // The fence makes sure that any future loads from `Atomic`s will not happen before
393
+ // this store.
394
+ if cfg!(all(
395
+ any(target_arch = "x86", target_arch = "x86_64"),
396
+ not(miri)
397
+ )) {
398
+ // HACK(stjepang): On x86 architectures there are two different ways of executing
399
+ // a `SeqCst` fence.
400
+ //
401
+ // 1. `atomic::fence(SeqCst)`, which compiles into a `mfence` instruction.
402
+ // 2. `_.compare_exchange(_, _, SeqCst, SeqCst)`, which compiles into a `lock cmpxchg`
403
+ // instruction.
404
+ //
405
+ // Both instructions have the effect of a full barrier, but benchmarks have shown
406
+ // that the second one makes pinning faster in this particular case. It is not
407
+ // clear that this is permitted by the C++ memory model (SC fences work very
408
+ // differently from SC accesses), but experimental evidence suggests that this
409
+ // works fine. Using inline assembly would be a viable (and correct) alternative,
410
+ // but alas, that is not possible on stable Rust.
411
+ let current = Epoch::starting();
412
+ let res = self.epoch.compare_exchange(
413
+ current,
414
+ new_epoch,
415
+ Ordering::SeqCst,
416
+ Ordering::SeqCst,
417
+ );
418
+ debug_assert!(res.is_ok(), "participant was expected to be unpinned");
419
+ // We add a compiler fence to make it less likely for LLVM to do something wrong
420
+ // here. Formally, this is not enough to get rid of data races; practically,
421
+ // it should go a long way.
422
+ atomic::compiler_fence(Ordering::SeqCst);
423
+ } else {
424
+ self.epoch.store(new_epoch, Ordering::Relaxed);
425
+ atomic::fence(Ordering::SeqCst);
426
+ }
427
+
428
+ // Increment the pin counter.
429
+ let count = self.pin_count.get();
430
+ self.pin_count.set(count + Wrapping(1));
431
+
432
+ // After every `PINNINGS_BETWEEN_COLLECT` try advancing the epoch and collecting
433
+ // some garbage.
434
+ if count.0 % Self::PINNINGS_BETWEEN_COLLECT == 0 {
435
+ self.global().collect(&guard);
436
+ }
437
+ }
438
+
439
+ guard
440
+ }
441
+
442
+ /// Unpins the `Local`.
443
+ #[inline]
444
+ pub(crate) fn unpin(&self) {
445
+ let guard_count = self.guard_count.get();
446
+ self.guard_count.set(guard_count - 1);
447
+
448
+ if guard_count == 1 {
449
+ self.epoch.store(Epoch::starting(), Ordering::Release);
450
+
451
+ if self.handle_count.get() == 0 {
452
+ self.finalize();
453
+ }
454
+ }
455
+ }
456
+
457
+ /// Unpins and then pins the `Local`.
458
+ #[inline]
459
+ pub(crate) fn repin(&self) {
460
+ let guard_count = self.guard_count.get();
461
+
462
+ // Update the local epoch only if there's only one guard.
463
+ if guard_count == 1 {
464
+ let epoch = self.epoch.load(Ordering::Relaxed);
465
+ let global_epoch = self.global().epoch.load(Ordering::Relaxed).pinned();
466
+
467
+ // Update the local epoch only if the global epoch is greater than the local epoch.
468
+ if epoch != global_epoch {
469
+ // We store the new epoch with `Release` because we need to ensure any memory
470
+ // accesses from the previous epoch do not leak into the new one.
471
+ self.epoch.store(global_epoch, Ordering::Release);
472
+
473
+ // However, we don't need a following `SeqCst` fence, because it is safe for memory
474
+ // accesses from the new epoch to be executed before updating the local epoch. At
475
+ // worse, other threads will see the new epoch late and delay GC slightly.
476
+ }
477
+ }
478
+ }
479
+
480
+ /// Increments the handle count.
481
+ #[inline]
482
+ pub(crate) fn acquire_handle(&self) {
483
+ let handle_count = self.handle_count.get();
484
+ debug_assert!(handle_count >= 1);
485
+ self.handle_count.set(handle_count + 1);
486
+ }
487
+
488
+ /// Decrements the handle count.
489
+ #[inline]
490
+ pub(crate) fn release_handle(&self) {
491
+ let guard_count = self.guard_count.get();
492
+ let handle_count = self.handle_count.get();
493
+ debug_assert!(handle_count >= 1);
494
+ self.handle_count.set(handle_count - 1);
495
+
496
+ if guard_count == 0 && handle_count == 1 {
497
+ self.finalize();
498
+ }
499
+ }
500
+
501
+ /// Removes the `Local` from the global linked list.
502
+ #[cold]
503
+ fn finalize(&self) {
504
+ debug_assert_eq!(self.guard_count.get(), 0);
505
+ debug_assert_eq!(self.handle_count.get(), 0);
506
+
507
+ // Temporarily increment handle count. This is required so that the following call to `pin`
508
+ // doesn't call `finalize` again.
509
+ self.handle_count.set(1);
510
+ unsafe {
511
+ // Pin and move the local bag into the global queue. It's important that `push_bag`
512
+ // doesn't defer destruction on any new garbage.
513
+ let guard = &self.pin();
514
+ self.global()
515
+ .push_bag(self.bag.with_mut(|b| &mut *b), guard);
516
+ }
517
+ // Revert the handle count back to zero.
518
+ self.handle_count.set(0);
519
+
520
+ unsafe {
521
+ // Take the reference to the `Global` out of this `Local`. Since we're not protected
522
+ // by a guard at this time, it's crucial that the reference is read before marking the
523
+ // `Local` as deleted.
524
+ let collector: Collector = ptr::read(self.collector.with(|c| &*(*c)));
525
+
526
+ // Mark this node in the linked list as deleted.
527
+ self.entry.delete(unprotected());
528
+
529
+ // Finally, drop the reference to the global. Note that this might be the last reference
530
+ // to the `Global`. If so, the global data will be destroyed and all deferred functions
531
+ // in its queue will be executed.
532
+ drop(collector);
533
+ }
534
+ }
535
+ }
536
+
537
+ impl IsElement<Self> for Local {
538
+ fn entry_of(local: &Self) -> &Entry {
539
+ // SAFETY: `Local` is `repr(C)` and `entry` is the first field of it.
540
+ unsafe {
541
+ let entry_ptr = (local as *const Self).cast::<Entry>();
542
+ &*entry_ptr
543
+ }
544
+ }
545
+
546
+ unsafe fn element_of(entry: &Entry) -> &Self {
547
+ // SAFETY: `Local` is `repr(C)` and `entry` is the first field of it.
548
+ let local_ptr = (entry as *const Entry).cast::<Self>();
549
+ &*local_ptr
550
+ }
551
+
552
+ unsafe fn finalize(entry: &Entry, guard: &Guard) {
553
+ guard.defer_destroy(Shared::from(Self::element_of(entry) as *const _));
554
+ }
555
+ }
556
+
557
+ #[cfg(all(test, not(crossbeam_loom)))]
558
+ mod tests {
559
+ use std::sync::atomic::{AtomicUsize, Ordering};
560
+
561
+ use super::*;
562
+
563
+ #[test]
564
+ fn check_defer() {
565
+ static FLAG: AtomicUsize = AtomicUsize::new(0);
566
+ fn set() {
567
+ FLAG.store(42, Ordering::Relaxed);
568
+ }
569
+
570
+ let d = Deferred::new(set);
571
+ assert_eq!(FLAG.load(Ordering::Relaxed), 0);
572
+ d.call();
573
+ assert_eq!(FLAG.load(Ordering::Relaxed), 42);
574
+ }
575
+
576
+ #[test]
577
+ fn check_bag() {
578
+ static FLAG: AtomicUsize = AtomicUsize::new(0);
579
+ fn incr() {
580
+ FLAG.fetch_add(1, Ordering::Relaxed);
581
+ }
582
+
583
+ let mut bag = Bag::new();
584
+ assert!(bag.is_empty());
585
+
586
+ for _ in 0..MAX_OBJECTS {
587
+ assert!(unsafe { bag.try_push(Deferred::new(incr)).is_ok() });
588
+ assert!(!bag.is_empty());
589
+ assert_eq!(FLAG.load(Ordering::Relaxed), 0);
590
+ }
591
+
592
+ let result = unsafe { bag.try_push(Deferred::new(incr)) };
593
+ assert!(result.is_err());
594
+ assert!(!bag.is_empty());
595
+ assert_eq!(FLAG.load(Ordering::Relaxed), 0);
596
+
597
+ drop(bag);
598
+ assert_eq!(FLAG.load(Ordering::Relaxed), MAX_OBJECTS);
599
+ }
600
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/lib.rs ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Epoch-based memory reclamation.
2
+ //!
3
+ //! An interesting problem concurrent collections deal with comes from the remove operation.
4
+ //! Suppose that a thread removes an element from a lock-free map, while another thread is reading
5
+ //! that same element at the same time. The first thread must wait until the second thread stops
6
+ //! reading the element. Only then it is safe to destruct it.
7
+ //!
8
+ //! Programming languages that come with garbage collectors solve this problem trivially. The
9
+ //! garbage collector will destruct the removed element when no thread can hold a reference to it
10
+ //! anymore.
11
+ //!
12
+ //! This crate implements a basic memory reclamation mechanism, which is based on epochs. When an
13
+ //! element gets removed from a concurrent collection, it is inserted into a pile of garbage and
14
+ //! marked with the current epoch. Every time a thread accesses a collection, it checks the current
15
+ //! epoch, attempts to increment it, and destructs some garbage that became so old that no thread
16
+ //! can be referencing it anymore.
17
+ //!
18
+ //! That is the general mechanism behind epoch-based memory reclamation, but the details are a bit
19
+ //! more complicated. Anyhow, memory reclamation is designed to be fully automatic and something
20
+ //! users of concurrent collections don't have to worry much about.
21
+ //!
22
+ //! # Pointers
23
+ //!
24
+ //! Concurrent collections are built using atomic pointers. This module provides [`Atomic`], which
25
+ //! is just a shared atomic pointer to a heap-allocated object. Loading an [`Atomic`] yields a
26
+ //! [`Shared`], which is an epoch-protected pointer through which the loaded object can be safely
27
+ //! read.
28
+ //!
29
+ //! # Pinning
30
+ //!
31
+ //! Before an [`Atomic`] can be loaded, a participant must be [`pin`]ned. By pinning a participant
32
+ //! we declare that any object that gets removed from now on must not be destructed just
33
+ //! yet. Garbage collection of newly removed objects is suspended until the participant gets
34
+ //! unpinned.
35
+ //!
36
+ //! # Garbage
37
+ //!
38
+ //! Objects that get removed from concurrent collections must be stashed away until all currently
39
+ //! pinned participants get unpinned. Such objects can be stored into a thread-local or global
40
+ //! storage, where they are kept until the right time for their destruction comes.
41
+ //!
42
+ //! There is a global shared instance of garbage queue. You can [`defer`](Guard::defer) the execution of an
43
+ //! arbitrary function until the global epoch is advanced enough. Most notably, concurrent data
44
+ //! structures may defer the deallocation of an object.
45
+ //!
46
+ //! # APIs
47
+ //!
48
+ //! For majority of use cases, just use the default garbage collector by invoking [`pin`]. If you
49
+ //! want to create your own garbage collector, use the [`Collector`] API.
50
+
51
+ #![doc(test(
52
+ no_crate_inject,
53
+ attr(
54
+ deny(warnings, rust_2018_idioms),
55
+ allow(dead_code, unused_assignments, unused_variables)
56
+ )
57
+ ))]
58
+ #![warn(
59
+ missing_docs,
60
+ missing_debug_implementations,
61
+ rust_2018_idioms,
62
+ unreachable_pub
63
+ )]
64
+ #![cfg_attr(not(feature = "std"), no_std)]
65
+
66
+ #[cfg(crossbeam_loom)]
67
+ extern crate loom_crate as loom;
68
+
69
+ #[cfg(crossbeam_loom)]
70
+ #[allow(unused_imports, dead_code)]
71
+ mod primitive {
72
+ pub(crate) mod cell {
73
+ pub(crate) use loom::cell::UnsafeCell;
74
+ }
75
+ pub(crate) mod sync {
76
+ pub(crate) mod atomic {
77
+ pub(crate) use loom::sync::atomic::{fence, AtomicPtr, AtomicUsize, Ordering};
78
+
79
+ // FIXME: loom does not support compiler_fence at the moment.
80
+ // https://github.com/tokio-rs/loom/issues/117
81
+ // we use fence as a stand-in for compiler_fence for the time being.
82
+ // this may miss some races since fence is stronger than compiler_fence,
83
+ // but it's the best we can do for the time being.
84
+ pub(crate) use self::fence as compiler_fence;
85
+ }
86
+ pub(crate) use loom::sync::Arc;
87
+ }
88
+ pub(crate) use loom::thread_local;
89
+ }
90
+ #[cfg(target_has_atomic = "ptr")]
91
+ #[cfg(not(crossbeam_loom))]
92
+ #[allow(unused_imports, dead_code)]
93
+ mod primitive {
94
+ pub(crate) mod cell {
95
+ #[derive(Debug)]
96
+ #[repr(transparent)]
97
+ pub(crate) struct UnsafeCell<T>(::core::cell::UnsafeCell<T>);
98
+
99
+ // loom's UnsafeCell has a slightly different API than the standard library UnsafeCell.
100
+ // Since we want the rest of the code to be agnostic to whether it's running under loom or
101
+ // not, we write this small wrapper that provides the loom-supported API for the standard
102
+ // library UnsafeCell. This is also what the loom documentation recommends:
103
+ // https://github.com/tokio-rs/loom#handling-loom-api-differences
104
+ impl<T> UnsafeCell<T> {
105
+ #[inline]
106
+ pub(crate) const fn new(data: T) -> UnsafeCell<T> {
107
+ UnsafeCell(::core::cell::UnsafeCell::new(data))
108
+ }
109
+
110
+ #[inline]
111
+ pub(crate) fn with<R>(&self, f: impl FnOnce(*const T) -> R) -> R {
112
+ f(self.0.get())
113
+ }
114
+
115
+ #[inline]
116
+ pub(crate) fn with_mut<R>(&self, f: impl FnOnce(*mut T) -> R) -> R {
117
+ f(self.0.get())
118
+ }
119
+ }
120
+ }
121
+ pub(crate) mod sync {
122
+ pub(crate) mod atomic {
123
+ pub(crate) use core::sync::atomic::{
124
+ compiler_fence, fence, AtomicPtr, AtomicUsize, Ordering,
125
+ };
126
+ }
127
+ #[cfg(feature = "alloc")]
128
+ pub(crate) use alloc::sync::Arc;
129
+ }
130
+
131
+ #[cfg(feature = "std")]
132
+ pub(crate) use std::thread_local;
133
+ }
134
+
135
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
136
+ extern crate alloc;
137
+
138
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
139
+ mod atomic;
140
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
141
+ mod collector;
142
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
143
+ mod deferred;
144
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
145
+ mod epoch;
146
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
147
+ mod guard;
148
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
149
+ mod internal;
150
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
151
+ mod sync;
152
+
153
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
154
+ #[allow(deprecated)]
155
+ pub use crate::atomic::{CompareAndSetError, CompareAndSetOrdering};
156
+ #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
157
+ pub use crate::{
158
+ atomic::{Atomic, CompareExchangeError, Owned, Pointable, Pointer, Shared},
159
+ collector::{Collector, LocalHandle},
160
+ guard::{unprotected, Guard},
161
+ };
162
+
163
+ #[cfg(feature = "std")]
164
+ mod default;
165
+ #[cfg(feature = "std")]
166
+ pub use crate::default::{default_collector, is_pinned, pin};
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/sync/list.rs ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Lock-free intrusive linked list.
2
+ //!
3
+ //! Ideas from Michael. High Performance Dynamic Lock-Free Hash Tables and List-Based Sets. SPAA
4
+ //! 2002. <http://dl.acm.org/citation.cfm?id=564870.564881>
5
+
6
+ use core::marker::PhantomData;
7
+ use core::sync::atomic::Ordering::{Acquire, Relaxed, Release};
8
+
9
+ use crate::{unprotected, Atomic, Guard, Shared};
10
+
11
+ /// An entry in a linked list.
12
+ ///
13
+ /// An Entry is accessed from multiple threads, so it would be beneficial to put it in a different
14
+ /// cache-line than thread-local data in terms of performance.
15
+ #[derive(Debug)]
16
+ pub(crate) struct Entry {
17
+ /// The next entry in the linked list.
18
+ /// If the tag is 1, this entry is marked as deleted.
19
+ next: Atomic<Entry>,
20
+ }
21
+
22
+ /// Implementing this trait asserts that the type `T` can be used as an element in the intrusive
23
+ /// linked list defined in this module. `T` has to contain (or otherwise be linked to) an instance
24
+ /// of `Entry`.
25
+ ///
26
+ /// # Example
27
+ ///
28
+ /// ```ignore
29
+ /// struct A {
30
+ /// entry: Entry,
31
+ /// data: usize,
32
+ /// }
33
+ ///
34
+ /// impl IsElement<A> for A {
35
+ /// fn entry_of(a: &A) -> &Entry {
36
+ /// let entry_ptr = ((a as usize) + offset_of!(A, entry)) as *const Entry;
37
+ /// unsafe { &*entry_ptr }
38
+ /// }
39
+ ///
40
+ /// unsafe fn element_of(entry: &Entry) -> &T {
41
+ /// let elem_ptr = ((entry as usize) - offset_of!(A, entry)) as *const T;
42
+ /// &*elem_ptr
43
+ /// }
44
+ ///
45
+ /// unsafe fn finalize(entry: &Entry, guard: &Guard) {
46
+ /// guard.defer_destroy(Shared::from(Self::element_of(entry) as *const _));
47
+ /// }
48
+ /// }
49
+ /// ```
50
+ ///
51
+ /// This trait is implemented on a type separate from `T` (although it can be just `T`), because
52
+ /// one type might be placeable into multiple lists, in which case it would require multiple
53
+ /// implementations of `IsElement`. In such cases, each struct implementing `IsElement<T>`
54
+ /// represents a distinct `Entry` in `T`.
55
+ ///
56
+ /// For example, we can insert the following struct into two lists using `entry1` for one
57
+ /// and `entry2` for the other:
58
+ ///
59
+ /// ```ignore
60
+ /// struct B {
61
+ /// entry1: Entry,
62
+ /// entry2: Entry,
63
+ /// data: usize,
64
+ /// }
65
+ /// ```
66
+ ///
67
+ pub(crate) trait IsElement<T> {
68
+ /// Returns a reference to this element's `Entry`.
69
+ fn entry_of(_: &T) -> &Entry;
70
+
71
+ /// Given a reference to an element's entry, returns that element.
72
+ ///
73
+ /// ```ignore
74
+ /// let elem = ListElement::new();
75
+ /// assert_eq!(elem.entry_of(),
76
+ /// unsafe { ListElement::element_of(elem.entry_of()) } );
77
+ /// ```
78
+ ///
79
+ /// # Safety
80
+ ///
81
+ /// The caller has to guarantee that the `Entry` is called with was retrieved from an instance
82
+ /// of the element type (`T`).
83
+ unsafe fn element_of(_: &Entry) -> &T;
84
+
85
+ /// The function that is called when an entry is unlinked from list.
86
+ ///
87
+ /// # Safety
88
+ ///
89
+ /// The caller has to guarantee that the `Entry` is called with was retrieved from an instance
90
+ /// of the element type (`T`).
91
+ unsafe fn finalize(_: &Entry, _: &Guard);
92
+ }
93
+
94
+ /// A lock-free, intrusive linked list of type `T`.
95
+ #[derive(Debug)]
96
+ pub(crate) struct List<T, C: IsElement<T> = T> {
97
+ /// The head of the linked list.
98
+ head: Atomic<Entry>,
99
+
100
+ /// The phantom data for using `T` and `C`.
101
+ _marker: PhantomData<(T, C)>,
102
+ }
103
+
104
+ /// An iterator used for retrieving values from the list.
105
+ pub(crate) struct Iter<'g, T, C: IsElement<T>> {
106
+ /// The guard that protects the iteration.
107
+ guard: &'g Guard,
108
+
109
+ /// Pointer from the predecessor to the current entry.
110
+ pred: &'g Atomic<Entry>,
111
+
112
+ /// The current entry.
113
+ curr: Shared<'g, Entry>,
114
+
115
+ /// The list head, needed for restarting iteration.
116
+ head: &'g Atomic<Entry>,
117
+
118
+ /// Logically, we store a borrow of an instance of `T` and
119
+ /// use the type information from `C`.
120
+ _marker: PhantomData<(&'g T, C)>,
121
+ }
122
+
123
+ /// An error that occurs during iteration over the list.
124
+ #[derive(PartialEq, Debug)]
125
+ pub(crate) enum IterError {
126
+ /// A concurrent thread modified the state of the list at the same place that this iterator
127
+ /// was inspecting. Subsequent iteration will restart from the beginning of the list.
128
+ Stalled,
129
+ }
130
+
131
+ impl Default for Entry {
132
+ /// Returns the empty entry.
133
+ fn default() -> Self {
134
+ Self {
135
+ next: Atomic::null(),
136
+ }
137
+ }
138
+ }
139
+
140
+ impl Entry {
141
+ /// Marks this entry as deleted, deferring the actual deallocation to a later iteration.
142
+ ///
143
+ /// # Safety
144
+ ///
145
+ /// The entry should be a member of a linked list, and it should not have been deleted.
146
+ /// It should be safe to call `C::finalize` on the entry after the `guard` is dropped, where `C`
147
+ /// is the associated helper for the linked list.
148
+ pub(crate) unsafe fn delete(&self, guard: &Guard) {
149
+ self.next.fetch_or(1, Release, guard);
150
+ }
151
+ }
152
+
153
+ impl<T, C: IsElement<T>> List<T, C> {
154
+ /// Returns a new, empty linked list.
155
+ pub(crate) fn new() -> Self {
156
+ Self {
157
+ head: Atomic::null(),
158
+ _marker: PhantomData,
159
+ }
160
+ }
161
+
162
+ /// Inserts `entry` into the head of the list.
163
+ ///
164
+ /// # Safety
165
+ ///
166
+ /// You should guarantee that:
167
+ ///
168
+ /// - `container` is not null
169
+ /// - `container` is immovable, e.g. inside an `Owned`
170
+ /// - the same `Entry` is not inserted more than once
171
+ /// - the inserted object will be removed before the list is dropped
172
+ pub(crate) unsafe fn insert<'g>(&'g self, container: Shared<'g, T>, guard: &'g Guard) {
173
+ // Insert right after head, i.e. at the beginning of the list.
174
+ let to = &self.head;
175
+ // Get the intrusively stored Entry of the new element to insert.
176
+ let entry: &Entry = C::entry_of(container.deref());
177
+ // Make a Shared ptr to that Entry.
178
+ let entry_ptr = Shared::from(entry as *const _);
179
+ // Read the current successor of where we want to insert.
180
+ let mut next = to.load(Relaxed, guard);
181
+
182
+ loop {
183
+ // Set the Entry of the to-be-inserted element to point to the previous successor of
184
+ // `to`.
185
+ entry.next.store(next, Relaxed);
186
+ match to.compare_exchange_weak(next, entry_ptr, Release, Relaxed, guard) {
187
+ Ok(_) => break,
188
+ // We lost the race or weak CAS failed spuriously. Update the successor and try
189
+ // again.
190
+ Err(err) => next = err.current,
191
+ }
192
+ }
193
+ }
194
+
195
+ /// Returns an iterator over all objects.
196
+ ///
197
+ /// # Caveat
198
+ ///
199
+ /// Every object that is inserted at the moment this function is called and persists at least
200
+ /// until the end of iteration will be returned. Since this iterator traverses a lock-free
201
+ /// linked list that may be concurrently modified, some additional caveats apply:
202
+ ///
203
+ /// 1. If a new object is inserted during iteration, it may or may not be returned.
204
+ /// 2. If an object is deleted during iteration, it may or may not be returned.
205
+ /// 3. The iteration may be aborted when it lost in a race condition. In this case, the winning
206
+ /// thread will continue to iterate over the same list.
207
+ pub(crate) fn iter<'g>(&'g self, guard: &'g Guard) -> Iter<'g, T, C> {
208
+ Iter {
209
+ guard,
210
+ pred: &self.head,
211
+ curr: self.head.load(Acquire, guard),
212
+ head: &self.head,
213
+ _marker: PhantomData,
214
+ }
215
+ }
216
+ }
217
+
218
+ impl<T, C: IsElement<T>> Drop for List<T, C> {
219
+ fn drop(&mut self) {
220
+ unsafe {
221
+ let guard = unprotected();
222
+ let mut curr = self.head.load(Relaxed, guard);
223
+ while let Some(c) = curr.as_ref() {
224
+ let succ = c.next.load(Relaxed, guard);
225
+ // Verify that all elements have been removed from the list.
226
+ assert_eq!(succ.tag(), 1);
227
+
228
+ C::finalize(curr.deref(), guard);
229
+ curr = succ;
230
+ }
231
+ }
232
+ }
233
+ }
234
+
235
+ impl<'g, T: 'g, C: IsElement<T>> Iterator for Iter<'g, T, C> {
236
+ type Item = Result<&'g T, IterError>;
237
+
238
+ fn next(&mut self) -> Option<Self::Item> {
239
+ while let Some(c) = unsafe { self.curr.as_ref() } {
240
+ let succ = c.next.load(Acquire, self.guard);
241
+
242
+ if succ.tag() == 1 {
243
+ // This entry was removed. Try unlinking it from the list.
244
+ let succ = succ.with_tag(0);
245
+
246
+ // The tag should always be zero, because removing a node after a logically deleted
247
+ // node leaves the list in an invalid state.
248
+ debug_assert!(self.curr.tag() == 0);
249
+
250
+ // Try to unlink `curr` from the list, and get the new value of `self.pred`.
251
+ let succ = match self
252
+ .pred
253
+ .compare_exchange(self.curr, succ, Acquire, Acquire, self.guard)
254
+ {
255
+ Ok(_) => {
256
+ // We succeeded in unlinking `curr`, so we have to schedule
257
+ // deallocation. Deferred drop is okay, because `list.delete()` can only be
258
+ // called if `T: 'static`.
259
+ unsafe {
260
+ C::finalize(self.curr.deref(), self.guard);
261
+ }
262
+
263
+ // `succ` is the new value of `self.pred`.
264
+ succ
265
+ }
266
+ Err(e) => {
267
+ // `e.current` is the current value of `self.pred`.
268
+ e.current
269
+ }
270
+ };
271
+
272
+ // If the predecessor node is already marked as deleted, we need to restart from
273
+ // `head`.
274
+ if succ.tag() != 0 {
275
+ self.pred = self.head;
276
+ self.curr = self.head.load(Acquire, self.guard);
277
+
278
+ return Some(Err(IterError::Stalled));
279
+ }
280
+
281
+ // Move over the removed by only advancing `curr`, not `pred`.
282
+ self.curr = succ;
283
+ continue;
284
+ }
285
+
286
+ // Move one step forward.
287
+ self.pred = &c.next;
288
+ self.curr = succ;
289
+
290
+ return Some(Ok(unsafe { C::element_of(c) }));
291
+ }
292
+
293
+ // We reached the end of the list.
294
+ None
295
+ }
296
+ }
297
+
298
+ #[cfg(all(test, not(crossbeam_loom)))]
299
+ mod tests {
300
+ use super::*;
301
+ use crate::{Collector, Owned};
302
+ use crossbeam_utils::thread;
303
+ use std::sync::Barrier;
304
+
305
+ impl IsElement<Entry> for Entry {
306
+ fn entry_of(entry: &Entry) -> &Entry {
307
+ entry
308
+ }
309
+
310
+ unsafe fn element_of(entry: &Entry) -> &Entry {
311
+ entry
312
+ }
313
+
314
+ unsafe fn finalize(entry: &Entry, guard: &Guard) {
315
+ guard.defer_destroy(Shared::from(Self::element_of(entry) as *const _));
316
+ }
317
+ }
318
+
319
+ /// Checks whether the list retains inserted elements
320
+ /// and returns them in the correct order.
321
+ #[test]
322
+ fn insert() {
323
+ let collector = Collector::new();
324
+ let handle = collector.register();
325
+ let guard = handle.pin();
326
+
327
+ let l: List<Entry> = List::new();
328
+
329
+ let e1 = Owned::new(Entry::default()).into_shared(&guard);
330
+ let e2 = Owned::new(Entry::default()).into_shared(&guard);
331
+ let e3 = Owned::new(Entry::default()).into_shared(&guard);
332
+
333
+ unsafe {
334
+ l.insert(e1, &guard);
335
+ l.insert(e2, &guard);
336
+ l.insert(e3, &guard);
337
+ }
338
+
339
+ let mut iter = l.iter(&guard);
340
+ let maybe_e3 = iter.next();
341
+ assert!(maybe_e3.is_some());
342
+ assert!(maybe_e3.unwrap().unwrap() as *const Entry == e3.as_raw());
343
+ let maybe_e2 = iter.next();
344
+ assert!(maybe_e2.is_some());
345
+ assert!(maybe_e2.unwrap().unwrap() as *const Entry == e2.as_raw());
346
+ let maybe_e1 = iter.next();
347
+ assert!(maybe_e1.is_some());
348
+ assert!(maybe_e1.unwrap().unwrap() as *const Entry == e1.as_raw());
349
+ assert!(iter.next().is_none());
350
+
351
+ unsafe {
352
+ e1.as_ref().unwrap().delete(&guard);
353
+ e2.as_ref().unwrap().delete(&guard);
354
+ e3.as_ref().unwrap().delete(&guard);
355
+ }
356
+ }
357
+
358
+ /// Checks whether elements can be removed from the list and whether
359
+ /// the correct elements are removed.
360
+ #[test]
361
+ fn delete() {
362
+ let collector = Collector::new();
363
+ let handle = collector.register();
364
+ let guard = handle.pin();
365
+
366
+ let l: List<Entry> = List::new();
367
+
368
+ let e1 = Owned::new(Entry::default()).into_shared(&guard);
369
+ let e2 = Owned::new(Entry::default()).into_shared(&guard);
370
+ let e3 = Owned::new(Entry::default()).into_shared(&guard);
371
+ unsafe {
372
+ l.insert(e1, &guard);
373
+ l.insert(e2, &guard);
374
+ l.insert(e3, &guard);
375
+ e2.as_ref().unwrap().delete(&guard);
376
+ }
377
+
378
+ let mut iter = l.iter(&guard);
379
+ let maybe_e3 = iter.next();
380
+ assert!(maybe_e3.is_some());
381
+ assert!(maybe_e3.unwrap().unwrap() as *const Entry == e3.as_raw());
382
+ let maybe_e1 = iter.next();
383
+ assert!(maybe_e1.is_some());
384
+ assert!(maybe_e1.unwrap().unwrap() as *const Entry == e1.as_raw());
385
+ assert!(iter.next().is_none());
386
+
387
+ unsafe {
388
+ e1.as_ref().unwrap().delete(&guard);
389
+ e3.as_ref().unwrap().delete(&guard);
390
+ }
391
+
392
+ let mut iter = l.iter(&guard);
393
+ assert!(iter.next().is_none());
394
+ }
395
+
396
+ const THREADS: usize = 8;
397
+ const ITERS: usize = 512;
398
+
399
+ /// Contends the list on insert and delete operations to make sure they can run concurrently.
400
+ #[test]
401
+ fn insert_delete_multi() {
402
+ let collector = Collector::new();
403
+
404
+ let l: List<Entry> = List::new();
405
+ let b = Barrier::new(THREADS);
406
+
407
+ thread::scope(|s| {
408
+ for _ in 0..THREADS {
409
+ s.spawn(|_| {
410
+ b.wait();
411
+
412
+ let handle = collector.register();
413
+ let guard: Guard = handle.pin();
414
+ let mut v = Vec::with_capacity(ITERS);
415
+
416
+ for _ in 0..ITERS {
417
+ let e = Owned::new(Entry::default()).into_shared(&guard);
418
+ v.push(e);
419
+ unsafe {
420
+ l.insert(e, &guard);
421
+ }
422
+ }
423
+
424
+ for e in v {
425
+ unsafe {
426
+ e.as_ref().unwrap().delete(&guard);
427
+ }
428
+ }
429
+ });
430
+ }
431
+ })
432
+ .unwrap();
433
+
434
+ let handle = collector.register();
435
+ let guard = handle.pin();
436
+
437
+ let mut iter = l.iter(&guard);
438
+ assert!(iter.next().is_none());
439
+ }
440
+
441
+ /// Contends the list on iteration to make sure that it can be iterated over concurrently.
442
+ #[test]
443
+ fn iter_multi() {
444
+ let collector = Collector::new();
445
+
446
+ let l: List<Entry> = List::new();
447
+ let b = Barrier::new(THREADS);
448
+
449
+ thread::scope(|s| {
450
+ for _ in 0..THREADS {
451
+ s.spawn(|_| {
452
+ b.wait();
453
+
454
+ let handle = collector.register();
455
+ let guard: Guard = handle.pin();
456
+ let mut v = Vec::with_capacity(ITERS);
457
+
458
+ for _ in 0..ITERS {
459
+ let e = Owned::new(Entry::default()).into_shared(&guard);
460
+ v.push(e);
461
+ unsafe {
462
+ l.insert(e, &guard);
463
+ }
464
+ }
465
+
466
+ let mut iter = l.iter(&guard);
467
+ for _ in 0..ITERS {
468
+ assert!(iter.next().is_some());
469
+ }
470
+
471
+ for e in v {
472
+ unsafe {
473
+ e.as_ref().unwrap().delete(&guard);
474
+ }
475
+ }
476
+ });
477
+ }
478
+ })
479
+ .unwrap();
480
+
481
+ let handle = collector.register();
482
+ let guard = handle.pin();
483
+
484
+ let mut iter = l.iter(&guard);
485
+ assert!(iter.next().is_none());
486
+ }
487
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/sync/mod.rs ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ //! Synchronization primitives.
2
+
3
+ pub(crate) mod list;
4
+ #[cfg(feature = "std")]
5
+ #[cfg(not(crossbeam_loom))]
6
+ pub(crate) mod once_lock;
7
+ pub(crate) mod queue;
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/sync/once_lock.rs ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Based on unstable std::sync::OnceLock.
2
+ //
3
+ // Source: https://github.com/rust-lang/rust/blob/8e9c93df464b7ada3fc7a1c8ccddd9dcb24ee0a0/library/std/src/sync/once_lock.rs
4
+
5
+ use core::cell::UnsafeCell;
6
+ use core::mem::MaybeUninit;
7
+ use std::sync::Once;
8
+
9
+ pub(crate) struct OnceLock<T> {
10
+ once: Once,
11
+ value: UnsafeCell<MaybeUninit<T>>,
12
+ // Unlike std::sync::OnceLock, we don't need PhantomData here because
13
+ // we don't use #[may_dangle].
14
+ }
15
+
16
+ unsafe impl<T: Sync + Send> Sync for OnceLock<T> {}
17
+ unsafe impl<T: Send> Send for OnceLock<T> {}
18
+
19
+ impl<T> OnceLock<T> {
20
+ /// Creates a new empty cell.
21
+ #[must_use]
22
+ pub(crate) const fn new() -> Self {
23
+ Self {
24
+ once: Once::new(),
25
+ value: UnsafeCell::new(MaybeUninit::uninit()),
26
+ }
27
+ }
28
+
29
+ /// Gets the contents of the cell, initializing it with `f` if the cell
30
+ /// was empty.
31
+ ///
32
+ /// Many threads may call `get_or_init` concurrently with different
33
+ /// initializing functions, but it is guaranteed that only one function
34
+ /// will be executed.
35
+ ///
36
+ /// # Panics
37
+ ///
38
+ /// If `f` panics, the panic is propagated to the caller, and the cell
39
+ /// remains uninitialized.
40
+ ///
41
+ /// It is an error to reentrantly initialize the cell from `f`. The
42
+ /// exact outcome is unspecified. Current implementation deadlocks, but
43
+ /// this may be changed to a panic in the future.
44
+ pub(crate) fn get_or_init<F>(&self, f: F) -> &T
45
+ where
46
+ F: FnOnce() -> T,
47
+ {
48
+ // Fast path check
49
+ if self.once.is_completed() {
50
+ // SAFETY: The inner value has been initialized
51
+ return unsafe { self.get_unchecked() };
52
+ }
53
+ self.initialize(f);
54
+
55
+ // SAFETY: The inner value has been initialized
56
+ unsafe { self.get_unchecked() }
57
+ }
58
+
59
+ #[cold]
60
+ fn initialize<F>(&self, f: F)
61
+ where
62
+ F: FnOnce() -> T,
63
+ {
64
+ let slot = self.value.get();
65
+
66
+ self.once.call_once(|| {
67
+ let value = f();
68
+ unsafe { slot.write(MaybeUninit::new(value)) }
69
+ });
70
+ }
71
+
72
+ /// # Safety
73
+ ///
74
+ /// The value must be initialized
75
+ unsafe fn get_unchecked(&self) -> &T {
76
+ debug_assert!(self.once.is_completed());
77
+ &*self.value.get().cast::<T>()
78
+ }
79
+ }
80
+
81
+ impl<T> Drop for OnceLock<T> {
82
+ fn drop(&mut self) {
83
+ if self.once.is_completed() {
84
+ // SAFETY: The inner value has been initialized
85
+ unsafe { (*self.value.get()).assume_init_drop() };
86
+ }
87
+ }
88
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/src/sync/queue.rs ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Michael-Scott lock-free queue.
2
+ //!
3
+ //! Usable with any number of producers and consumers.
4
+ //!
5
+ //! Michael and Scott. Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue
6
+ //! Algorithms. PODC 1996. <http://dl.acm.org/citation.cfm?id=248106>
7
+ //!
8
+ //! Simon Doherty, Lindsay Groves, Victor Luchangco, and Mark Moir. 2004b. Formal Verification of a
9
+ //! Practical Lock-Free Queue Algorithm. <https://doi.org/10.1007/978-3-540-30232-2_7>
10
+
11
+ use core::mem::MaybeUninit;
12
+ use core::sync::atomic::Ordering::{Acquire, Relaxed, Release};
13
+
14
+ use crossbeam_utils::CachePadded;
15
+
16
+ use crate::{unprotected, Atomic, Guard, Owned, Shared};
17
+
18
+ // The representation here is a singly-linked list, with a sentinel node at the front. In general
19
+ // the `tail` pointer may lag behind the actual tail. Non-sentinel nodes are either all `Data` or
20
+ // all `Blocked` (requests for data from blocked threads).
21
+ #[derive(Debug)]
22
+ pub(crate) struct Queue<T> {
23
+ head: CachePadded<Atomic<Node<T>>>,
24
+ tail: CachePadded<Atomic<Node<T>>>,
25
+ }
26
+
27
+ struct Node<T> {
28
+ /// The slot in which a value of type `T` can be stored.
29
+ ///
30
+ /// The type of `data` is `MaybeUninit<T>` because a `Node<T>` doesn't always contain a `T`.
31
+ /// For example, the sentinel node in a queue never contains a value: its slot is always empty.
32
+ /// Other nodes start their life with a push operation and contain a value until it gets popped
33
+ /// out. After that such empty nodes get added to the collector for destruction.
34
+ data: MaybeUninit<T>,
35
+
36
+ next: Atomic<Node<T>>,
37
+ }
38
+
39
+ // Any particular `T` should never be accessed concurrently, so no need for `Sync`.
40
+ unsafe impl<T: Send> Sync for Queue<T> {}
41
+ unsafe impl<T: Send> Send for Queue<T> {}
42
+
43
+ impl<T> Queue<T> {
44
+ /// Create a new, empty queue.
45
+ pub(crate) fn new() -> Queue<T> {
46
+ let q = Queue {
47
+ head: CachePadded::new(Atomic::null()),
48
+ tail: CachePadded::new(Atomic::null()),
49
+ };
50
+ let sentinel = Owned::new(Node {
51
+ data: MaybeUninit::uninit(),
52
+ next: Atomic::null(),
53
+ });
54
+ unsafe {
55
+ let guard = unprotected();
56
+ let sentinel = sentinel.into_shared(guard);
57
+ q.head.store(sentinel, Relaxed);
58
+ q.tail.store(sentinel, Relaxed);
59
+ q
60
+ }
61
+ }
62
+
63
+ /// Attempts to atomically place `n` into the `next` pointer of `onto`, and returns `true` on
64
+ /// success. The queue's `tail` pointer may be updated.
65
+ #[inline(always)]
66
+ fn push_internal(
67
+ &self,
68
+ onto: Shared<'_, Node<T>>,
69
+ new: Shared<'_, Node<T>>,
70
+ guard: &Guard,
71
+ ) -> bool {
72
+ // is `onto` the actual tail?
73
+ let o = unsafe { onto.deref() };
74
+ let next = o.next.load(Acquire, guard);
75
+ if unsafe { next.as_ref().is_some() } {
76
+ // if not, try to "help" by moving the tail pointer forward
77
+ let _ = self
78
+ .tail
79
+ .compare_exchange(onto, next, Release, Relaxed, guard);
80
+ false
81
+ } else {
82
+ // looks like the actual tail; attempt to link in `n`
83
+ let result = o
84
+ .next
85
+ .compare_exchange(Shared::null(), new, Release, Relaxed, guard)
86
+ .is_ok();
87
+ if result {
88
+ // try to move the tail pointer forward
89
+ let _ = self
90
+ .tail
91
+ .compare_exchange(onto, new, Release, Relaxed, guard);
92
+ }
93
+ result
94
+ }
95
+ }
96
+
97
+ /// Adds `t` to the back of the queue, possibly waking up threads blocked on `pop`.
98
+ pub(crate) fn push(&self, t: T, guard: &Guard) {
99
+ let new = Owned::new(Node {
100
+ data: MaybeUninit::new(t),
101
+ next: Atomic::null(),
102
+ });
103
+ let new = Owned::into_shared(new, guard);
104
+
105
+ loop {
106
+ // We push onto the tail, so we'll start optimistically by looking there first.
107
+ let tail = self.tail.load(Acquire, guard);
108
+
109
+ // Attempt to push onto the `tail` snapshot; fails if `tail.next` has changed.
110
+ if self.push_internal(tail, new, guard) {
111
+ break;
112
+ }
113
+ }
114
+ }
115
+
116
+ /// Attempts to pop a data node. `Ok(None)` if queue is empty; `Err(())` if lost race to pop.
117
+ #[inline(always)]
118
+ fn pop_internal(&self, guard: &Guard) -> Result<Option<T>, ()> {
119
+ let head = self.head.load(Acquire, guard);
120
+ let h = unsafe { head.deref() };
121
+ let next = h.next.load(Acquire, guard);
122
+ match unsafe { next.as_ref() } {
123
+ Some(n) => unsafe {
124
+ self.head
125
+ .compare_exchange(head, next, Release, Relaxed, guard)
126
+ .map(|_| {
127
+ let tail = self.tail.load(Relaxed, guard);
128
+ // Advance the tail so that we don't retire a pointer to a reachable node.
129
+ if head == tail {
130
+ let _ = self
131
+ .tail
132
+ .compare_exchange(tail, next, Release, Relaxed, guard);
133
+ }
134
+ guard.defer_destroy(head);
135
+ Some(n.data.assume_init_read())
136
+ })
137
+ .map_err(|_| ())
138
+ },
139
+ None => Ok(None),
140
+ }
141
+ }
142
+
143
+ /// Attempts to pop a data node, if the data satisfies the given condition. `Ok(None)` if queue
144
+ /// is empty or the data does not satisfy the condition; `Err(())` if lost race to pop.
145
+ #[inline(always)]
146
+ fn pop_if_internal<F>(&self, condition: F, guard: &Guard) -> Result<Option<T>, ()>
147
+ where
148
+ T: Sync,
149
+ F: Fn(&T) -> bool,
150
+ {
151
+ let head = self.head.load(Acquire, guard);
152
+ let h = unsafe { head.deref() };
153
+ let next = h.next.load(Acquire, guard);
154
+ match unsafe { next.as_ref() } {
155
+ Some(n) if condition(unsafe { &*n.data.as_ptr() }) => unsafe {
156
+ self.head
157
+ .compare_exchange(head, next, Release, Relaxed, guard)
158
+ .map(|_| {
159
+ let tail = self.tail.load(Relaxed, guard);
160
+ // Advance the tail so that we don't retire a pointer to a reachable node.
161
+ if head == tail {
162
+ let _ = self
163
+ .tail
164
+ .compare_exchange(tail, next, Release, Relaxed, guard);
165
+ }
166
+ guard.defer_destroy(head);
167
+ Some(n.data.assume_init_read())
168
+ })
169
+ .map_err(|_| ())
170
+ },
171
+ None | Some(_) => Ok(None),
172
+ }
173
+ }
174
+
175
+ /// Attempts to dequeue from the front.
176
+ ///
177
+ /// Returns `None` if the queue is observed to be empty.
178
+ pub(crate) fn try_pop(&self, guard: &Guard) -> Option<T> {
179
+ loop {
180
+ if let Ok(head) = self.pop_internal(guard) {
181
+ return head;
182
+ }
183
+ }
184
+ }
185
+
186
+ /// Attempts to dequeue from the front, if the item satisfies the given condition.
187
+ ///
188
+ /// Returns `None` if the queue is observed to be empty, or the head does not satisfy the given
189
+ /// condition.
190
+ pub(crate) fn try_pop_if<F>(&self, condition: F, guard: &Guard) -> Option<T>
191
+ where
192
+ T: Sync,
193
+ F: Fn(&T) -> bool,
194
+ {
195
+ loop {
196
+ if let Ok(head) = self.pop_if_internal(&condition, guard) {
197
+ return head;
198
+ }
199
+ }
200
+ }
201
+ }
202
+
203
+ impl<T> Drop for Queue<T> {
204
+ fn drop(&mut self) {
205
+ unsafe {
206
+ let guard = unprotected();
207
+
208
+ while self.try_pop(guard).is_some() {}
209
+
210
+ // Destroy the remaining sentinel node.
211
+ let sentinel = self.head.load(Relaxed, guard);
212
+ drop(sentinel.into_owned());
213
+ }
214
+ }
215
+ }
216
+
217
+ #[cfg(all(test, not(crossbeam_loom)))]
218
+ mod test {
219
+ use super::*;
220
+ use crate::pin;
221
+ use crossbeam_utils::thread;
222
+
223
+ struct Queue<T> {
224
+ queue: super::Queue<T>,
225
+ }
226
+
227
+ impl<T> Queue<T> {
228
+ pub(crate) fn new() -> Queue<T> {
229
+ Queue {
230
+ queue: super::Queue::new(),
231
+ }
232
+ }
233
+
234
+ pub(crate) fn push(&self, t: T) {
235
+ let guard = &pin();
236
+ self.queue.push(t, guard);
237
+ }
238
+
239
+ pub(crate) fn is_empty(&self) -> bool {
240
+ let guard = &pin();
241
+ let head = self.queue.head.load(Acquire, guard);
242
+ let h = unsafe { head.deref() };
243
+ h.next.load(Acquire, guard).is_null()
244
+ }
245
+
246
+ pub(crate) fn try_pop(&self) -> Option<T> {
247
+ let guard = &pin();
248
+ self.queue.try_pop(guard)
249
+ }
250
+
251
+ pub(crate) fn pop(&self) -> T {
252
+ loop {
253
+ match self.try_pop() {
254
+ None => continue,
255
+ Some(t) => return t,
256
+ }
257
+ }
258
+ }
259
+ }
260
+
261
+ #[cfg(miri)]
262
+ const CONC_COUNT: i64 = 1000;
263
+ #[cfg(not(miri))]
264
+ const CONC_COUNT: i64 = 1000000;
265
+
266
+ #[test]
267
+ fn push_try_pop_1() {
268
+ let q: Queue<i64> = Queue::new();
269
+ assert!(q.is_empty());
270
+ q.push(37);
271
+ assert!(!q.is_empty());
272
+ assert_eq!(q.try_pop(), Some(37));
273
+ assert!(q.is_empty());
274
+ }
275
+
276
+ #[test]
277
+ fn push_try_pop_2() {
278
+ let q: Queue<i64> = Queue::new();
279
+ assert!(q.is_empty());
280
+ q.push(37);
281
+ q.push(48);
282
+ assert_eq!(q.try_pop(), Some(37));
283
+ assert!(!q.is_empty());
284
+ assert_eq!(q.try_pop(), Some(48));
285
+ assert!(q.is_empty());
286
+ }
287
+
288
+ #[test]
289
+ fn push_try_pop_many_seq() {
290
+ let q: Queue<i64> = Queue::new();
291
+ assert!(q.is_empty());
292
+ for i in 0..200 {
293
+ q.push(i)
294
+ }
295
+ assert!(!q.is_empty());
296
+ for i in 0..200 {
297
+ assert_eq!(q.try_pop(), Some(i));
298
+ }
299
+ assert!(q.is_empty());
300
+ }
301
+
302
+ #[test]
303
+ fn push_pop_1() {
304
+ let q: Queue<i64> = Queue::new();
305
+ assert!(q.is_empty());
306
+ q.push(37);
307
+ assert!(!q.is_empty());
308
+ assert_eq!(q.pop(), 37);
309
+ assert!(q.is_empty());
310
+ }
311
+
312
+ #[test]
313
+ fn push_pop_2() {
314
+ let q: Queue<i64> = Queue::new();
315
+ q.push(37);
316
+ q.push(48);
317
+ assert_eq!(q.pop(), 37);
318
+ assert_eq!(q.pop(), 48);
319
+ }
320
+
321
+ #[test]
322
+ fn push_pop_many_seq() {
323
+ let q: Queue<i64> = Queue::new();
324
+ assert!(q.is_empty());
325
+ for i in 0..200 {
326
+ q.push(i)
327
+ }
328
+ assert!(!q.is_empty());
329
+ for i in 0..200 {
330
+ assert_eq!(q.pop(), i);
331
+ }
332
+ assert!(q.is_empty());
333
+ }
334
+
335
+ #[test]
336
+ fn push_try_pop_many_spsc() {
337
+ let q: Queue<i64> = Queue::new();
338
+ assert!(q.is_empty());
339
+
340
+ thread::scope(|scope| {
341
+ scope.spawn(|_| {
342
+ let mut next = 0;
343
+
344
+ while next < CONC_COUNT {
345
+ if let Some(elem) = q.try_pop() {
346
+ assert_eq!(elem, next);
347
+ next += 1;
348
+ }
349
+ }
350
+ });
351
+
352
+ for i in 0..CONC_COUNT {
353
+ q.push(i)
354
+ }
355
+ })
356
+ .unwrap();
357
+ }
358
+
359
+ #[test]
360
+ fn push_try_pop_many_spmc() {
361
+ fn recv(_t: i32, q: &Queue<i64>) {
362
+ let mut cur = -1;
363
+ for _i in 0..CONC_COUNT {
364
+ if let Some(elem) = q.try_pop() {
365
+ assert!(elem > cur);
366
+ cur = elem;
367
+
368
+ if cur == CONC_COUNT - 1 {
369
+ break;
370
+ }
371
+ }
372
+ }
373
+ }
374
+
375
+ let q: Queue<i64> = Queue::new();
376
+ assert!(q.is_empty());
377
+ thread::scope(|scope| {
378
+ for i in 0..3 {
379
+ let q = &q;
380
+ scope.spawn(move |_| recv(i, q));
381
+ }
382
+
383
+ scope.spawn(|_| {
384
+ for i in 0..CONC_COUNT {
385
+ q.push(i);
386
+ }
387
+ });
388
+ })
389
+ .unwrap();
390
+ }
391
+
392
+ #[test]
393
+ fn push_try_pop_many_mpmc() {
394
+ enum LR {
395
+ Left(i64),
396
+ Right(i64),
397
+ }
398
+
399
+ let q: Queue<LR> = Queue::new();
400
+ assert!(q.is_empty());
401
+
402
+ thread::scope(|scope| {
403
+ for _t in 0..2 {
404
+ scope.spawn(|_| {
405
+ for i in CONC_COUNT - 1..CONC_COUNT {
406
+ q.push(LR::Left(i))
407
+ }
408
+ });
409
+ scope.spawn(|_| {
410
+ for i in CONC_COUNT - 1..CONC_COUNT {
411
+ q.push(LR::Right(i))
412
+ }
413
+ });
414
+ scope.spawn(|_| {
415
+ let mut vl = vec![];
416
+ let mut vr = vec![];
417
+ for _i in 0..CONC_COUNT {
418
+ match q.try_pop() {
419
+ Some(LR::Left(x)) => vl.push(x),
420
+ Some(LR::Right(x)) => vr.push(x),
421
+ _ => {}
422
+ }
423
+ }
424
+
425
+ let mut vl2 = vl.clone();
426
+ let mut vr2 = vr.clone();
427
+ vl2.sort_unstable();
428
+ vr2.sort_unstable();
429
+
430
+ assert_eq!(vl, vl2);
431
+ assert_eq!(vr, vr2);
432
+ });
433
+ }
434
+ })
435
+ .unwrap();
436
+ }
437
+
438
+ #[test]
439
+ fn push_pop_many_spsc() {
440
+ let q: Queue<i64> = Queue::new();
441
+
442
+ thread::scope(|scope| {
443
+ scope.spawn(|_| {
444
+ let mut next = 0;
445
+ while next < CONC_COUNT {
446
+ assert_eq!(q.pop(), next);
447
+ next += 1;
448
+ }
449
+ });
450
+
451
+ for i in 0..CONC_COUNT {
452
+ q.push(i)
453
+ }
454
+ })
455
+ .unwrap();
456
+ assert!(q.is_empty());
457
+ }
458
+
459
+ #[test]
460
+ fn is_empty_dont_pop() {
461
+ let q: Queue<i64> = Queue::new();
462
+ q.push(20);
463
+ q.push(20);
464
+ assert!(!q.is_empty());
465
+ assert!(!q.is_empty());
466
+ assert!(q.try_pop().is_some());
467
+ }
468
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/crossbeam-epoch-0.9.18/tests/loom.rs ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![cfg(crossbeam_loom)]
2
+
3
+ use crossbeam_epoch as epoch;
4
+ use loom_crate as loom;
5
+
6
+ use epoch::*;
7
+ use epoch::{Atomic, Owned};
8
+ use loom::sync::atomic::Ordering::{self, Acquire, Relaxed, Release};
9
+ use loom::sync::Arc;
10
+ use loom::thread::spawn;
11
+ use std::mem::ManuallyDrop;
12
+ use std::ptr;
13
+
14
+ #[test]
15
+ fn it_works() {
16
+ loom::model(|| {
17
+ let collector = Collector::new();
18
+ let item: Atomic<String> = Atomic::from(Owned::new(String::from("boom")));
19
+ let item2 = item.clone();
20
+ let collector2 = collector.clone();
21
+ let guard = collector.register().pin();
22
+
23
+ let jh = loom::thread::spawn(move || {
24
+ let guard = collector2.register().pin();
25
+ guard.defer(move || {
26
+ // this isn't really safe, since other threads may still have pointers to the
27
+ // value, but in this limited test scenario it's okay, since we know the test won't
28
+ // access item after all the pins are released.
29
+ let mut item = unsafe { item2.into_owned() };
30
+ // mutate it as a second measure to make sure the assert_eq below would fail
31
+ item.retain(|c| c == 'o');
32
+ drop(item);
33
+ });
34
+ });
35
+
36
+ let item = item.load(Ordering::SeqCst, &guard);
37
+ // we pinned strictly before the call to defer_destroy,
38
+ // so item cannot have been dropped yet
39
+ assert_eq!(*unsafe { item.deref() }, "boom");
40
+ drop(guard);
41
+
42
+ jh.join().unwrap();
43
+
44
+ drop(collector);
45
+ })
46
+ }
47
+
48
+ #[test]
49
+ fn treiber_stack() {
50
+ /// Treiber's lock-free stack.
51
+ ///
52
+ /// Usable with any number of producers and consumers.
53
+ #[derive(Debug)]
54
+ pub struct TreiberStack<T> {
55
+ head: Atomic<Node<T>>,
56
+ }
57
+
58
+ #[derive(Debug)]
59
+ struct Node<T> {
60
+ data: ManuallyDrop<T>,
61
+ next: Atomic<Node<T>>,
62
+ }
63
+
64
+ impl<T> TreiberStack<T> {
65
+ /// Creates a new, empty stack.
66
+ pub fn new() -> TreiberStack<T> {
67
+ TreiberStack {
68
+ head: Atomic::null(),
69
+ }
70
+ }
71
+
72
+ /// Pushes a value on top of the stack.
73
+ pub fn push(&self, t: T) {
74
+ let mut n = Owned::new(Node {
75
+ data: ManuallyDrop::new(t),
76
+ next: Atomic::null(),
77
+ });
78
+
79
+ let guard = epoch::pin();
80
+
81
+ loop {
82
+ let head = self.head.load(Relaxed, &guard);
83
+ n.next.store(head, Relaxed);
84
+
85
+ match self
86
+ .head
87
+ .compare_exchange(head, n, Release, Relaxed, &guard)
88
+ {
89
+ Ok(_) => break,
90
+ Err(e) => n = e.new,
91
+ }
92
+ }
93
+ }
94
+
95
+ /// Attempts to pop the top element from the stack.
96
+ ///
97
+ /// Returns `None` if the stack is empty.
98
+ pub fn pop(&self) -> Option<T> {
99
+ let guard = epoch::pin();
100
+ loop {
101
+ let head = self.head.load(Acquire, &guard);
102
+
103
+ match unsafe { head.as_ref() } {
104
+ Some(h) => {
105
+ let next = h.next.load(Relaxed, &guard);
106
+
107
+ if self
108
+ .head
109
+ .compare_exchange(head, next, Relaxed, Relaxed, &guard)
110
+ .is_ok()
111
+ {
112
+ unsafe {
113
+ guard.defer_destroy(head);
114
+ return Some(ManuallyDrop::into_inner(ptr::read(&(*h).data)));
115
+ }
116
+ }
117
+ }
118
+ None => return None,
119
+ }
120
+ }
121
+ }
122
+
123
+ /// Returns `true` if the stack is empty.
124
+ pub fn is_empty(&self) -> bool {
125
+ let guard = epoch::pin();
126
+ self.head.load(Acquire, &guard).is_null()
127
+ }
128
+ }
129
+
130
+ impl<T> Drop for TreiberStack<T> {
131
+ fn drop(&mut self) {
132
+ while self.pop().is_some() {}
133
+ }
134
+ }
135
+
136
+ loom::model(|| {
137
+ let stack1 = Arc::new(TreiberStack::new());
138
+ let stack2 = Arc::clone(&stack1);
139
+
140
+ // use 5 since it's greater than the 4 used for the sanitize feature
141
+ let jh = spawn(move || {
142
+ for i in 0..5 {
143
+ stack2.push(i);
144
+ assert!(stack2.pop().is_some());
145
+ }
146
+ });
147
+
148
+ for i in 0..5 {
149
+ stack1.push(i);
150
+ assert!(stack1.pop().is_some());
151
+ }
152
+
153
+ jh.join().unwrap();
154
+ assert!(stack1.pop().is_none());
155
+ assert!(stack1.is_empty());
156
+ });
157
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/src/hex.rs ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Hexadecimal encoding support
2
+ // TODO(tarcieri): use `base16ct`?
3
+
4
+ use crate::{ComponentBytes, Error, Signature};
5
+ use core::{fmt, str};
6
+
7
+ /// Format a signature component as hex.
8
+ pub(crate) struct ComponentFormatter<'a>(pub(crate) &'a ComponentBytes);
9
+
10
+ impl fmt::Debug for ComponentFormatter<'_> {
11
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12
+ write!(f, "0x")?;
13
+
14
+ for byte in self.0 {
15
+ write!(f, "{:02x}", byte)?;
16
+ }
17
+
18
+ Ok(())
19
+ }
20
+ }
21
+
22
+ impl fmt::LowerHex for Signature {
23
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24
+ for component in [&self.R, &self.s] {
25
+ for byte in component {
26
+ write!(f, "{:02x}", byte)?;
27
+ }
28
+ }
29
+ Ok(())
30
+ }
31
+ }
32
+
33
+ impl fmt::UpperHex for Signature {
34
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35
+ for component in [&self.R, &self.s] {
36
+ for byte in component {
37
+ write!(f, "{:02X}", byte)?;
38
+ }
39
+ }
40
+ Ok(())
41
+ }
42
+ }
43
+
44
+ /// Decode a signature from hexadecimal.
45
+ ///
46
+ /// Upper and lower case hexadecimal are both accepted, however mixed case is
47
+ /// rejected.
48
+ // TODO(tarcieri): use `base16ct`?
49
+ impl str::FromStr for Signature {
50
+ type Err = Error;
51
+
52
+ fn from_str(hex: &str) -> signature::Result<Self> {
53
+ if hex.as_bytes().len() != Signature::BYTE_SIZE * 2 {
54
+ return Err(Error::new());
55
+ }
56
+
57
+ let mut upper_case = None;
58
+
59
+ // Ensure all characters are valid and case is not mixed
60
+ for &byte in hex.as_bytes() {
61
+ match byte {
62
+ b'0'..=b'9' => (),
63
+ b'a'..=b'z' => match upper_case {
64
+ Some(true) => return Err(Error::new()),
65
+ Some(false) => (),
66
+ None => upper_case = Some(false),
67
+ },
68
+ b'A'..=b'Z' => match upper_case {
69
+ Some(true) => (),
70
+ Some(false) => return Err(Error::new()),
71
+ None => upper_case = Some(true),
72
+ },
73
+ _ => return Err(Error::new()),
74
+ }
75
+ }
76
+
77
+ let mut result = [0u8; Self::BYTE_SIZE];
78
+ for (digit, byte) in hex.as_bytes().chunks_exact(2).zip(result.iter_mut()) {
79
+ *byte = str::from_utf8(digit)
80
+ .ok()
81
+ .and_then(|s| u8::from_str_radix(s, 16).ok())
82
+ .ok_or_else(Error::new)?;
83
+ }
84
+
85
+ Self::try_from(&result[..])
86
+ }
87
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/src/lib.rs ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![no_std]
2
+ #![cfg_attr(docsrs, feature(doc_auto_cfg))]
3
+ #![doc = include_str!("../README.md")]
4
+ #![doc(html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")]
5
+ #![allow(non_snake_case)]
6
+ #![forbid(unsafe_code)]
7
+ #![warn(
8
+ clippy::unwrap_used,
9
+ missing_docs,
10
+ rust_2018_idioms,
11
+ unused_lifetimes,
12
+ unused_qualifications
13
+ )]
14
+
15
+ //! # Using Ed25519 generically over algorithm implementations/providers
16
+ //!
17
+ //! By using the `ed25519` crate, you can write code which signs and verifies
18
+ //! messages using the Ed25519 signature algorithm generically over any
19
+ //! supported Ed25519 implementation (see the next section for available
20
+ //! providers).
21
+ //!
22
+ //! This allows consumers of your code to plug in whatever implementation they
23
+ //! want to use without having to add all potential Ed25519 libraries you'd
24
+ //! like to support as optional dependencies.
25
+ //!
26
+ //! ## Example
27
+ //!
28
+ //! ```
29
+ //! use ed25519::signature::{Signer, Verifier};
30
+ //!
31
+ //! pub struct HelloSigner<S>
32
+ //! where
33
+ //! S: Signer<ed25519::Signature>
34
+ //! {
35
+ //! pub signing_key: S
36
+ //! }
37
+ //!
38
+ //! impl<S> HelloSigner<S>
39
+ //! where
40
+ //! S: Signer<ed25519::Signature>
41
+ //! {
42
+ //! pub fn sign(&self, person: &str) -> ed25519::Signature {
43
+ //! // NOTE: use `try_sign` if you'd like to be able to handle
44
+ //! // errors from external signing services/devices (e.g. HSM/KMS)
45
+ //! // <https://docs.rs/signature/latest/signature/trait.Signer.html#tymethod.try_sign>
46
+ //! self.signing_key.sign(format_message(person).as_bytes())
47
+ //! }
48
+ //! }
49
+ //!
50
+ //! pub struct HelloVerifier<V> {
51
+ //! pub verifying_key: V
52
+ //! }
53
+ //!
54
+ //! impl<V> HelloVerifier<V>
55
+ //! where
56
+ //! V: Verifier<ed25519::Signature>
57
+ //! {
58
+ //! pub fn verify(
59
+ //! &self,
60
+ //! person: &str,
61
+ //! signature: &ed25519::Signature
62
+ //! ) -> Result<(), ed25519::Error> {
63
+ //! self.verifying_key.verify(format_message(person).as_bytes(), signature)
64
+ //! }
65
+ //! }
66
+ //!
67
+ //! fn format_message(person: &str) -> String {
68
+ //! format!("Hello, {}!", person)
69
+ //! }
70
+ //! ```
71
+ //!
72
+ //! ## Using above example with `ed25519-dalek`
73
+ //!
74
+ //! The [`ed25519-dalek`] crate natively supports the [`ed25519::Signature`][`Signature`]
75
+ //! type defined in this crate along with the [`signature::Signer`] and
76
+ //! [`signature::Verifier`] traits.
77
+ //!
78
+ //! Below is an example of how a hypothetical consumer of the code above can
79
+ //! instantiate and use the previously defined `HelloSigner` and `HelloVerifier`
80
+ //! types with [`ed25519-dalek`] as the signing/verification provider:
81
+ //!
82
+ //! *NOTE: requires [`ed25519-dalek`] v2 or newer for compatibility with
83
+ //! `ed25519` v2.2+*.
84
+ //!
85
+ //! ```
86
+ //! use ed25519_dalek::{Signer, Verifier, Signature};
87
+ //! #
88
+ //! # pub struct HelloSigner<S>
89
+ //! # where
90
+ //! # S: Signer<Signature>
91
+ //! # {
92
+ //! # pub signing_key: S
93
+ //! # }
94
+ //! #
95
+ //! # impl<S> HelloSigner<S>
96
+ //! # where
97
+ //! # S: Signer<Signature>
98
+ //! # {
99
+ //! # pub fn sign(&self, person: &str) -> Signature {
100
+ //! # // NOTE: use `try_sign` if you'd like to be able to handle
101
+ //! # // errors from external signing services/devices (e.g. HSM/KMS)
102
+ //! # // <https://docs.rs/signature/latest/signature/trait.Signer.html#tymethod.try_sign>
103
+ //! # self.signing_key.sign(format_message(person).as_bytes())
104
+ //! # }
105
+ //! # }
106
+ //! #
107
+ //! # pub struct HelloVerifier<V> {
108
+ //! # pub verifying_key: V
109
+ //! # }
110
+ //! #
111
+ //! # impl<V> HelloVerifier<V>
112
+ //! # where
113
+ //! # V: Verifier<Signature>
114
+ //! # {
115
+ //! # pub fn verify(
116
+ //! # &self,
117
+ //! # person: &str,
118
+ //! # signature: &Signature
119
+ //! # ) -> Result<(), ed25519::Error> {
120
+ //! # self.verifying_key.verify(format_message(person).as_bytes(), signature)
121
+ //! # }
122
+ //! # }
123
+ //! #
124
+ //! # fn format_message(person: &str) -> String {
125
+ //! # format!("Hello, {}!", person)
126
+ //! # }
127
+ //! use rand_core::OsRng; // Requires the `std` feature of `rand_core`
128
+ //!
129
+ //! /// `HelloSigner` defined above instantiated with `ed25519-dalek` as
130
+ //! /// the signing provider.
131
+ //! pub type DalekHelloSigner = HelloSigner<ed25519_dalek::SigningKey>;
132
+ //!
133
+ //! let signing_key = ed25519_dalek::SigningKey::generate(&mut OsRng);
134
+ //! let signer = DalekHelloSigner { signing_key };
135
+ //! let person = "Joe"; // Message to sign
136
+ //! let signature = signer.sign(person);
137
+ //!
138
+ //! /// `HelloVerifier` defined above instantiated with `ed25519-dalek`
139
+ //! /// as the signature verification provider.
140
+ //! pub type DalekHelloVerifier = HelloVerifier<ed25519_dalek::VerifyingKey>;
141
+ //!
142
+ //! let verifying_key: ed25519_dalek::VerifyingKey = signer.signing_key.verifying_key();
143
+ //! let verifier = DalekHelloVerifier { verifying_key };
144
+ //! assert!(verifier.verify(person, &signature).is_ok());
145
+ //! ```
146
+ //!
147
+ //! ## Using above example with `ring-compat`
148
+ //!
149
+ //! The [`ring-compat`] crate provides wrappers for [*ring*] which implement
150
+ //! the [`signature::Signer`] and [`signature::Verifier`] traits for
151
+ //! [`ed25519::Signature`][`Signature`].
152
+ //!
153
+ //! Below is an example of how a hypothetical consumer of the code above can
154
+ //! instantiate and use the previously defined `HelloSigner` and `HelloVerifier`
155
+ //! types with [`ring-compat`] as the signing/verification provider:
156
+ //!
157
+ //! ```
158
+ //! use ring_compat::signature::{
159
+ //! ed25519::{Signature, SigningKey, VerifyingKey},
160
+ //! Signer, Verifier
161
+ //! };
162
+ //! #
163
+ //! # pub struct HelloSigner<S>
164
+ //! # where
165
+ //! # S: Signer<Signature>
166
+ //! # {
167
+ //! # pub signing_key: S
168
+ //! # }
169
+ //! #
170
+ //! # impl<S> HelloSigner<S>
171
+ //! # where
172
+ //! # S: Signer<Signature>
173
+ //! # {
174
+ //! # pub fn sign(&self, person: &str) -> Signature {
175
+ //! # // NOTE: use `try_sign` if you'd like to be able to handle
176
+ //! # // errors from external signing services/devices (e.g. HSM/KMS)
177
+ //! # // <https://docs.rs/signature/latest/signature/trait.Signer.html#tymethod.try_sign>
178
+ //! # self.signing_key.sign(format_message(person).as_bytes())
179
+ //! # }
180
+ //! # }
181
+ //! #
182
+ //! # pub struct HelloVerifier<V> {
183
+ //! # pub verifying_key: V
184
+ //! # }
185
+ //! #
186
+ //! # impl<V> HelloVerifier<V>
187
+ //! # where
188
+ //! # V: Verifier<Signature>
189
+ //! # {
190
+ //! # pub fn verify(
191
+ //! # &self,
192
+ //! # person: &str,
193
+ //! # signature: &Signature
194
+ //! # ) -> Result<(), ed25519::Error> {
195
+ //! # self.verifying_key.verify(format_message(person).as_bytes(), signature)
196
+ //! # }
197
+ //! # }
198
+ //! #
199
+ //! # fn format_message(person: &str) -> String {
200
+ //! # format!("Hello, {}!", person)
201
+ //! # }
202
+ //! use rand_core::{OsRng, RngCore}; // Requires the `std` feature of `rand_core`
203
+ //!
204
+ //! /// `HelloSigner` defined above instantiated with *ring* as
205
+ //! /// the signing provider.
206
+ //! pub type RingHelloSigner = HelloSigner<SigningKey>;
207
+ //!
208
+ //! let mut ed25519_seed = [0u8; 32];
209
+ //! OsRng.fill_bytes(&mut ed25519_seed);
210
+ //!
211
+ //! let signing_key = SigningKey::from_bytes(&ed25519_seed);
212
+ //! let verifying_key = signing_key.verifying_key();
213
+ //!
214
+ //! let signer = RingHelloSigner { signing_key };
215
+ //! let person = "Joe"; // Message to sign
216
+ //! let signature = signer.sign(person);
217
+ //!
218
+ //! /// `HelloVerifier` defined above instantiated with *ring*
219
+ //! /// as the signature verification provider.
220
+ //! pub type RingHelloVerifier = HelloVerifier<VerifyingKey>;
221
+ //!
222
+ //! let verifier = RingHelloVerifier { verifying_key };
223
+ //! assert!(verifier.verify(person, &signature).is_ok());
224
+ //! ```
225
+ //!
226
+ //! # Available Ed25519 providers
227
+ //!
228
+ //! The following libraries support the types/traits from the `ed25519` crate:
229
+ //!
230
+ //! - [`ed25519-dalek`] - mature pure Rust implementation of Ed25519
231
+ //! - [`ring-compat`] - compatibility wrapper for [*ring*]
232
+ //! - [`yubihsm`] - host-side client library for YubiHSM2 devices from Yubico
233
+ //!
234
+ //! [`ed25519-dalek`]: https://docs.rs/ed25519-dalek
235
+ //! [`ring-compat`]: https://docs.rs/ring-compat
236
+ //! [*ring*]: https://github.com/briansmith/ring
237
+ //! [`yubihsm`]: https://github.com/iqlusioninc/yubihsm.rs/blob/develop/README.md
238
+ //!
239
+ //! # Features
240
+ //!
241
+ //! The following features are presently supported:
242
+ //!
243
+ //! - `pkcs8`: support for decoding/encoding PKCS#8-formatted private keys using the
244
+ //! [`KeypairBytes`] type.
245
+ //! - `std` *(default)*: Enable `std` support in [`signature`], which currently only affects whether
246
+ //! [`signature::Error`] implements `std::error::Error`.
247
+ //! - `serde`: Implement `serde::Deserialize` and `serde::Serialize` for [`Signature`]. Signatures
248
+ //! are serialized as their bytes.
249
+ //! - `serde_bytes`: Implement `serde_bytes::Deserialize` and `serde_bytes::Serialize` for
250
+ //! [`Signature`]. This enables more compact representations for formats with an efficient byte
251
+ //! array representation. As per the `serde_bytes` documentation, this can most easily be realised
252
+ //! using the `#[serde(with = "serde_bytes")]` annotation, e.g.:
253
+ //!
254
+ //! ```ignore
255
+ //! # use ed25519::Signature;
256
+ //! # use serde::{Deserialize, Serialize};
257
+ //! #[derive(Deserialize, Serialize)]
258
+ //! #[serde(transparent)]
259
+ //! struct SignatureAsBytes(#[serde(with = "serde_bytes")] Signature);
260
+ //! ```
261
+
262
+ #[cfg(feature = "alloc")]
263
+ extern crate alloc;
264
+
265
+ mod hex;
266
+
267
+ #[cfg(feature = "pkcs8")]
268
+ pub mod pkcs8;
269
+
270
+ #[cfg(feature = "serde")]
271
+ mod serde;
272
+
273
+ pub use signature::{self, Error, SignatureEncoding};
274
+
275
+ #[cfg(feature = "pkcs8")]
276
+ pub use crate::pkcs8::{KeypairBytes, PublicKeyBytes};
277
+
278
+ use core::fmt;
279
+
280
+ #[cfg(feature = "alloc")]
281
+ use alloc::vec::Vec;
282
+
283
+ /// Size of a single component of an Ed25519 signature.
284
+ const COMPONENT_SIZE: usize = 32;
285
+
286
+ /// Size of an `R` or `s` component of an Ed25519 signature when serialized
287
+ /// as bytes.
288
+ pub type ComponentBytes = [u8; COMPONENT_SIZE];
289
+
290
+ /// Ed25519 signature serialized as a byte array.
291
+ pub type SignatureBytes = [u8; Signature::BYTE_SIZE];
292
+
293
+ /// Ed25519 signature.
294
+ ///
295
+ /// This type represents a container for the byte serialization of an Ed25519
296
+ /// signature, and does not necessarily represent well-formed field or curve
297
+ /// elements.
298
+ ///
299
+ /// Signature verification libraries are expected to reject invalid field
300
+ /// elements at the time a signature is verified.
301
+ #[derive(Copy, Clone, Eq, PartialEq)]
302
+ #[repr(C)]
303
+ pub struct Signature {
304
+ R: ComponentBytes,
305
+ s: ComponentBytes,
306
+ }
307
+
308
+ impl Signature {
309
+ /// Size of an encoded Ed25519 signature in bytes.
310
+ pub const BYTE_SIZE: usize = COMPONENT_SIZE * 2;
311
+
312
+ /// Parse an Ed25519 signature from a byte slice.
313
+ pub fn from_bytes(bytes: &SignatureBytes) -> Self {
314
+ let mut R = ComponentBytes::default();
315
+ let mut s = ComponentBytes::default();
316
+
317
+ let components = bytes.split_at(COMPONENT_SIZE);
318
+ R.copy_from_slice(components.0);
319
+ s.copy_from_slice(components.1);
320
+
321
+ Self { R, s }
322
+ }
323
+
324
+ /// Parse an Ed25519 signature from its `R` and `s` components.
325
+ pub fn from_components(R: ComponentBytes, s: ComponentBytes) -> Self {
326
+ Self { R, s }
327
+ }
328
+
329
+ /// Parse an Ed25519 signature from a byte slice.
330
+ ///
331
+ /// # Returns
332
+ /// - `Ok` on success
333
+ /// - `Err` if the input byte slice is not 64-bytes
334
+ pub fn from_slice(bytes: &[u8]) -> signature::Result<Self> {
335
+ SignatureBytes::try_from(bytes)
336
+ .map(Into::into)
337
+ .map_err(|_| Error::new())
338
+ }
339
+
340
+ /// Bytes for the `R` component of a signature.
341
+ pub fn r_bytes(&self) -> &ComponentBytes {
342
+ &self.R
343
+ }
344
+
345
+ /// Bytes for the `s` component of a signature.
346
+ pub fn s_bytes(&self) -> &ComponentBytes {
347
+ &self.s
348
+ }
349
+
350
+ /// Return the inner byte array.
351
+ pub fn to_bytes(&self) -> SignatureBytes {
352
+ let mut ret = [0u8; Self::BYTE_SIZE];
353
+ let (R, s) = ret.split_at_mut(COMPONENT_SIZE);
354
+ R.copy_from_slice(&self.R);
355
+ s.copy_from_slice(&self.s);
356
+ ret
357
+ }
358
+
359
+ /// Convert this signature into a byte vector.
360
+ #[cfg(feature = "alloc")]
361
+ pub fn to_vec(&self) -> Vec<u8> {
362
+ self.to_bytes().to_vec()
363
+ }
364
+ }
365
+
366
+ impl SignatureEncoding for Signature {
367
+ type Repr = SignatureBytes;
368
+
369
+ fn to_bytes(&self) -> SignatureBytes {
370
+ self.to_bytes()
371
+ }
372
+ }
373
+
374
+ impl From<Signature> for SignatureBytes {
375
+ fn from(sig: Signature) -> SignatureBytes {
376
+ sig.to_bytes()
377
+ }
378
+ }
379
+
380
+ impl From<&Signature> for SignatureBytes {
381
+ fn from(sig: &Signature) -> SignatureBytes {
382
+ sig.to_bytes()
383
+ }
384
+ }
385
+
386
+ impl From<SignatureBytes> for Signature {
387
+ fn from(bytes: SignatureBytes) -> Self {
388
+ Signature::from_bytes(&bytes)
389
+ }
390
+ }
391
+
392
+ impl From<&SignatureBytes> for Signature {
393
+ fn from(bytes: &SignatureBytes) -> Self {
394
+ Signature::from_bytes(bytes)
395
+ }
396
+ }
397
+
398
+ impl TryFrom<&[u8]> for Signature {
399
+ type Error = Error;
400
+
401
+ fn try_from(bytes: &[u8]) -> signature::Result<Self> {
402
+ Self::from_slice(bytes)
403
+ }
404
+ }
405
+
406
+ impl fmt::Debug for Signature {
407
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408
+ f.debug_struct("ed25519::Signature")
409
+ .field("R", &hex::ComponentFormatter(self.r_bytes()))
410
+ .field("s", &hex::ComponentFormatter(self.s_bytes()))
411
+ .finish()
412
+ }
413
+ }
414
+
415
+ impl fmt::Display for Signature {
416
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417
+ write!(f, "{:X}", self)
418
+ }
419
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/src/pkcs8.rs ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! PKCS#8 private key support.
2
+ //!
3
+ //! Implements Ed25519 PKCS#8 private keys as described in RFC8410 Section 7:
4
+ //! <https://datatracker.ietf.org/doc/html/rfc8410#section-7>
5
+ //!
6
+ //! ## SemVer Notes
7
+ //!
8
+ //! The `pkcs8` module of this crate is exempted from SemVer as it uses a
9
+ //! pre-1.0 dependency (the `pkcs8` crate).
10
+ //!
11
+ //! However, breaking changes to this module will be accompanied by a minor
12
+ //! version bump.
13
+ //!
14
+ //! Please lock to a specific minor version of the `ed25519` crate to avoid
15
+ //! breaking changes when using this module.
16
+
17
+ pub use pkcs8::{
18
+ spki, DecodePrivateKey, DecodePublicKey, Error, ObjectIdentifier, PrivateKeyInfo, Result,
19
+ };
20
+
21
+ #[cfg(feature = "alloc")]
22
+ pub use pkcs8::{spki::EncodePublicKey, EncodePrivateKey};
23
+
24
+ #[cfg(feature = "alloc")]
25
+ pub use pkcs8::der::{asn1::BitStringRef, Document, SecretDocument};
26
+
27
+ use core::fmt;
28
+
29
+ #[cfg(feature = "pem")]
30
+ use {
31
+ alloc::string::{String, ToString},
32
+ core::str,
33
+ };
34
+
35
+ #[cfg(feature = "zeroize")]
36
+ use zeroize::Zeroize;
37
+
38
+ /// Algorithm [`ObjectIdentifier`] for the Ed25519 digital signature algorithm
39
+ /// (`id-Ed25519`).
40
+ ///
41
+ /// <http://oid-info.com/get/1.3.101.112>
42
+ pub const ALGORITHM_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
43
+
44
+ /// Ed25519 Algorithm Identifier.
45
+ pub const ALGORITHM_ID: pkcs8::AlgorithmIdentifierRef<'static> = pkcs8::AlgorithmIdentifierRef {
46
+ oid: ALGORITHM_OID,
47
+ parameters: None,
48
+ };
49
+
50
+ /// Ed25519 keypair serialized as bytes.
51
+ ///
52
+ /// This type is primarily useful for decoding/encoding PKCS#8 private key
53
+ /// files (either DER or PEM) encoded using the following traits:
54
+ ///
55
+ /// - [`DecodePrivateKey`]: decode DER or PEM encoded PKCS#8 private key.
56
+ /// - [`EncodePrivateKey`]: encode DER or PEM encoded PKCS#8 private key.
57
+ ///
58
+ /// PKCS#8 private key files encoded with PEM begin with:
59
+ ///
60
+ /// ```text
61
+ /// -----BEGIN PRIVATE KEY-----
62
+ /// ```
63
+ ///
64
+ /// Note that this type operates on raw bytes and performs no validation that
65
+ /// keys represent valid Ed25519 field elements.
66
+ pub struct KeypairBytes {
67
+ /// Ed25519 secret key.
68
+ ///
69
+ /// Little endian serialization of an element of the Curve25519 scalar
70
+ /// field, prior to "clamping" (i.e. setting/clearing bits to ensure the
71
+ /// scalar is actually a valid field element)
72
+ pub secret_key: [u8; Self::BYTE_SIZE / 2],
73
+
74
+ /// Ed25519 public key (if available).
75
+ ///
76
+ /// Compressed Edwards-y encoded curve point.
77
+ pub public_key: Option<PublicKeyBytes>,
78
+ }
79
+
80
+ impl KeypairBytes {
81
+ /// Size of an Ed25519 keypair when serialized as bytes.
82
+ const BYTE_SIZE: usize = 64;
83
+
84
+ /// Parse raw keypair from a 64-byte input.
85
+ pub fn from_bytes(bytes: &[u8; Self::BYTE_SIZE]) -> Self {
86
+ let (sk, pk) = bytes.split_at(Self::BYTE_SIZE / 2);
87
+
88
+ Self {
89
+ secret_key: sk.try_into().expect("secret key size error"),
90
+ public_key: Some(PublicKeyBytes(
91
+ pk.try_into().expect("public key size error"),
92
+ )),
93
+ }
94
+ }
95
+
96
+ /// Serialize as a 64-byte keypair.
97
+ ///
98
+ /// # Returns
99
+ ///
100
+ /// - `Some(bytes)` if the `public_key` is present.
101
+ /// - `None` if the `public_key` is absent (i.e. `None`).
102
+ pub fn to_bytes(&self) -> Option<[u8; Self::BYTE_SIZE]> {
103
+ if let Some(public_key) = &self.public_key {
104
+ let mut result = [0u8; Self::BYTE_SIZE];
105
+ let (sk, pk) = result.split_at_mut(Self::BYTE_SIZE / 2);
106
+ sk.copy_from_slice(&self.secret_key);
107
+ pk.copy_from_slice(public_key.as_ref());
108
+ Some(result)
109
+ } else {
110
+ None
111
+ }
112
+ }
113
+ }
114
+
115
+ impl Drop for KeypairBytes {
116
+ fn drop(&mut self) {
117
+ #[cfg(feature = "zeroize")]
118
+ self.secret_key.zeroize()
119
+ }
120
+ }
121
+
122
+ #[cfg(feature = "alloc")]
123
+ impl EncodePrivateKey for KeypairBytes {
124
+ fn to_pkcs8_der(&self) -> Result<SecretDocument> {
125
+ // Serialize private key as nested OCTET STRING
126
+ let mut private_key = [0u8; 2 + (Self::BYTE_SIZE / 2)];
127
+ private_key[0] = 0x04;
128
+ private_key[1] = 0x20;
129
+ private_key[2..].copy_from_slice(&self.secret_key);
130
+
131
+ let private_key_info = PrivateKeyInfo {
132
+ algorithm: ALGORITHM_ID,
133
+ private_key: &private_key,
134
+ public_key: self.public_key.as_ref().map(|pk| pk.0.as_slice()),
135
+ };
136
+
137
+ let result = SecretDocument::encode_msg(&private_key_info)?;
138
+
139
+ #[cfg(feature = "zeroize")]
140
+ private_key.zeroize();
141
+
142
+ Ok(result)
143
+ }
144
+ }
145
+
146
+ impl TryFrom<PrivateKeyInfo<'_>> for KeypairBytes {
147
+ type Error = Error;
148
+
149
+ fn try_from(private_key: PrivateKeyInfo<'_>) -> Result<Self> {
150
+ private_key.algorithm.assert_algorithm_oid(ALGORITHM_OID)?;
151
+
152
+ if private_key.algorithm.parameters.is_some() {
153
+ return Err(Error::ParametersMalformed);
154
+ }
155
+
156
+ // Ed25519 PKCS#8 keys are represented as a nested OCTET STRING
157
+ // (i.e. an OCTET STRING within an OCTET STRING).
158
+ //
159
+ // This match statement checks and removes the inner OCTET STRING
160
+ // header value:
161
+ //
162
+ // - 0x04: OCTET STRING tag
163
+ // - 0x20: 32-byte length
164
+ let secret_key = match private_key.private_key {
165
+ [0x04, 0x20, rest @ ..] => rest.try_into().map_err(|_| Error::KeyMalformed),
166
+ _ => Err(Error::KeyMalformed),
167
+ }?;
168
+
169
+ let public_key = private_key
170
+ .public_key
171
+ .map(|bytes| bytes.try_into().map_err(|_| Error::KeyMalformed))
172
+ .transpose()?
173
+ .map(PublicKeyBytes);
174
+
175
+ Ok(Self {
176
+ secret_key,
177
+ public_key,
178
+ })
179
+ }
180
+ }
181
+
182
+ impl TryFrom<&[u8]> for KeypairBytes {
183
+ type Error = Error;
184
+
185
+ fn try_from(der_bytes: &[u8]) -> Result<Self> {
186
+ Self::from_pkcs8_der(der_bytes)
187
+ }
188
+ }
189
+
190
+ impl fmt::Debug for KeypairBytes {
191
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192
+ f.debug_struct("KeypairBytes")
193
+ .field("public_key", &self.public_key)
194
+ .finish_non_exhaustive()
195
+ }
196
+ }
197
+
198
+ #[cfg(feature = "pem")]
199
+ impl str::FromStr for KeypairBytes {
200
+ type Err = Error;
201
+
202
+ fn from_str(pem: &str) -> Result<Self> {
203
+ Self::from_pkcs8_pem(pem)
204
+ }
205
+ }
206
+
207
+ /// Ed25519 public key serialized as bytes.
208
+ ///
209
+ /// This type is primarily useful for decoding/encoding SPKI public key
210
+ /// files (either DER or PEM) encoded using the following traits:
211
+ ///
212
+ /// - [`DecodePublicKey`]: decode DER or PEM encoded PKCS#8 private key.
213
+ /// - [`EncodePublicKey`]: encode DER or PEM encoded PKCS#8 private key.
214
+ ///
215
+ /// SPKI public key files encoded with PEM begin with:
216
+ ///
217
+ /// ```text
218
+ /// -----BEGIN PUBLIC KEY-----
219
+ /// ```
220
+ ///
221
+ /// Note that this type operates on raw bytes and performs no validation that
222
+ /// public keys represent valid compressed Ed25519 y-coordinates.
223
+ #[derive(Clone, Copy, Eq, PartialEq)]
224
+ pub struct PublicKeyBytes(pub [u8; Self::BYTE_SIZE]);
225
+
226
+ impl PublicKeyBytes {
227
+ /// Size of an Ed25519 public key when serialized as bytes.
228
+ const BYTE_SIZE: usize = 32;
229
+
230
+ /// Returns the raw bytes of the public key.
231
+ pub fn to_bytes(&self) -> [u8; Self::BYTE_SIZE] {
232
+ self.0
233
+ }
234
+ }
235
+
236
+ impl AsRef<[u8; Self::BYTE_SIZE]> for PublicKeyBytes {
237
+ fn as_ref(&self) -> &[u8; Self::BYTE_SIZE] {
238
+ &self.0
239
+ }
240
+ }
241
+
242
+ #[cfg(feature = "alloc")]
243
+ impl EncodePublicKey for PublicKeyBytes {
244
+ fn to_public_key_der(&self) -> spki::Result<Document> {
245
+ pkcs8::SubjectPublicKeyInfoRef {
246
+ algorithm: ALGORITHM_ID,
247
+ subject_public_key: BitStringRef::new(0, &self.0)?,
248
+ }
249
+ .try_into()
250
+ }
251
+ }
252
+
253
+ impl TryFrom<spki::SubjectPublicKeyInfoRef<'_>> for PublicKeyBytes {
254
+ type Error = spki::Error;
255
+
256
+ fn try_from(spki: spki::SubjectPublicKeyInfoRef<'_>) -> spki::Result<Self> {
257
+ spki.algorithm.assert_algorithm_oid(ALGORITHM_OID)?;
258
+
259
+ if spki.algorithm.parameters.is_some() {
260
+ return Err(spki::Error::KeyMalformed);
261
+ }
262
+
263
+ spki.subject_public_key
264
+ .as_bytes()
265
+ .ok_or(spki::Error::KeyMalformed)?
266
+ .try_into()
267
+ .map(Self)
268
+ .map_err(|_| spki::Error::KeyMalformed)
269
+ }
270
+ }
271
+
272
+ impl TryFrom<&[u8]> for PublicKeyBytes {
273
+ type Error = spki::Error;
274
+
275
+ fn try_from(der_bytes: &[u8]) -> spki::Result<Self> {
276
+ Self::from_public_key_der(der_bytes)
277
+ }
278
+ }
279
+
280
+ impl TryFrom<KeypairBytes> for PublicKeyBytes {
281
+ type Error = spki::Error;
282
+
283
+ fn try_from(keypair: KeypairBytes) -> spki::Result<PublicKeyBytes> {
284
+ PublicKeyBytes::try_from(&keypair)
285
+ }
286
+ }
287
+
288
+ impl TryFrom<&KeypairBytes> for PublicKeyBytes {
289
+ type Error = spki::Error;
290
+
291
+ fn try_from(keypair: &KeypairBytes) -> spki::Result<PublicKeyBytes> {
292
+ keypair.public_key.ok_or(spki::Error::KeyMalformed)
293
+ }
294
+ }
295
+
296
+ impl fmt::Debug for PublicKeyBytes {
297
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298
+ f.write_str("PublicKeyBytes(")?;
299
+
300
+ for &byte in self.as_ref() {
301
+ write!(f, "{:02X}", byte)?;
302
+ }
303
+
304
+ f.write_str(")")
305
+ }
306
+ }
307
+
308
+ #[cfg(feature = "pem")]
309
+ impl str::FromStr for PublicKeyBytes {
310
+ type Err = spki::Error;
311
+
312
+ fn from_str(pem: &str) -> spki::Result<Self> {
313
+ Self::from_public_key_pem(pem)
314
+ }
315
+ }
316
+
317
+ #[cfg(feature = "pem")]
318
+ impl ToString for PublicKeyBytes {
319
+ fn to_string(&self) -> String {
320
+ self.to_public_key_pem(Default::default())
321
+ .expect("PEM serialization error")
322
+ }
323
+ }
324
+
325
+ #[cfg(feature = "pem")]
326
+ #[cfg(test)]
327
+ mod tests {
328
+ use super::{KeypairBytes, PublicKeyBytes};
329
+ use hex_literal::hex;
330
+
331
+ const SECRET_KEY_BYTES: [u8; 32] =
332
+ hex!("D4EE72DBF913584AD5B6D8F1F769F8AD3AFE7C28CBF1D4FBE097A88F44755842");
333
+
334
+ const PUBLIC_KEY_BYTES: [u8; 32] =
335
+ hex!("19BF44096984CDFE8541BAC167DC3B96C85086AA30B6B6CB0C5C38AD703166E1");
336
+
337
+ #[test]
338
+ fn to_bytes() {
339
+ let valid_keypair = KeypairBytes {
340
+ secret_key: SECRET_KEY_BYTES,
341
+ public_key: Some(PublicKeyBytes(PUBLIC_KEY_BYTES)),
342
+ };
343
+
344
+ assert_eq!(
345
+ valid_keypair.to_bytes().unwrap(),
346
+ hex!("D4EE72DBF913584AD5B6D8F1F769F8AD3AFE7C28CBF1D4FBE097A88F4475584219BF44096984CDFE8541BAC167DC3B96C85086AA30B6B6CB0C5C38AD703166E1")
347
+ );
348
+
349
+ let invalid_keypair = KeypairBytes {
350
+ secret_key: SECRET_KEY_BYTES,
351
+ public_key: None,
352
+ };
353
+
354
+ assert_eq!(invalid_keypair.to_bytes(), None);
355
+ }
356
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/src/serde.rs ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! `serde` support.
2
+
3
+ use crate::{Signature, SignatureBytes};
4
+ use ::serde::{de, ser, Deserialize, Serialize};
5
+ use core::fmt;
6
+
7
+ impl Serialize for Signature {
8
+ fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
9
+ use ser::SerializeTuple;
10
+
11
+ let mut seq = serializer.serialize_tuple(Signature::BYTE_SIZE)?;
12
+
13
+ for byte in self.to_bytes() {
14
+ seq.serialize_element(&byte)?;
15
+ }
16
+
17
+ seq.end()
18
+ }
19
+ }
20
+
21
+ // serde lacks support for deserializing arrays larger than 32-bytes
22
+ // see: <https://github.com/serde-rs/serde/issues/631>
23
+ impl<'de> Deserialize<'de> for Signature {
24
+ fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
25
+ struct ByteArrayVisitor;
26
+
27
+ impl<'de> de::Visitor<'de> for ByteArrayVisitor {
28
+ type Value = [u8; Signature::BYTE_SIZE];
29
+
30
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31
+ formatter.write_str("bytestring of length 64")
32
+ }
33
+
34
+ fn visit_seq<A>(self, mut seq: A) -> Result<[u8; Signature::BYTE_SIZE], A::Error>
35
+ where
36
+ A: de::SeqAccess<'de>,
37
+ {
38
+ use de::Error;
39
+ let mut arr = [0u8; Signature::BYTE_SIZE];
40
+
41
+ for (i, byte) in arr.iter_mut().enumerate() {
42
+ *byte = seq
43
+ .next_element()?
44
+ .ok_or_else(|| Error::invalid_length(i, &self))?;
45
+ }
46
+
47
+ Ok(arr)
48
+ }
49
+ }
50
+
51
+ deserializer
52
+ .deserialize_tuple(Signature::BYTE_SIZE, ByteArrayVisitor)
53
+ .map(Into::into)
54
+ }
55
+ }
56
+
57
+ #[cfg(feature = "serde_bytes")]
58
+ impl serde_bytes::Serialize for Signature {
59
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60
+ where
61
+ S: serde::Serializer,
62
+ {
63
+ serializer.serialize_bytes(&self.to_bytes())
64
+ }
65
+ }
66
+
67
+ #[cfg(feature = "serde_bytes")]
68
+ impl<'de> serde_bytes::Deserialize<'de> for Signature {
69
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
70
+ where
71
+ D: de::Deserializer<'de>,
72
+ {
73
+ struct ByteArrayVisitor;
74
+
75
+ impl<'de> de::Visitor<'de> for ByteArrayVisitor {
76
+ type Value = SignatureBytes;
77
+
78
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79
+ formatter.write_str("bytestring of length 64")
80
+ }
81
+
82
+ fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
83
+ where
84
+ E: de::Error,
85
+ {
86
+ use de::Error;
87
+
88
+ bytes
89
+ .try_into()
90
+ .map_err(|_| Error::invalid_length(bytes.len(), &self))
91
+ }
92
+ }
93
+
94
+ deserializer
95
+ .deserialize_bytes(ByteArrayVisitor)
96
+ .map(Into::into)
97
+ }
98
+ }
99
+
100
+ #[cfg(test)]
101
+ mod tests {
102
+ use crate::{Signature, SignatureBytes};
103
+ use hex_literal::hex;
104
+
105
+ const SIGNATURE_BYTES: SignatureBytes = hex!(
106
+ "
107
+ e5564300c360ac729086e2cc806e828a
108
+ 84877f1eb8e5d974d873e06522490155
109
+ 5fb8821590a33bacc61e39701cf9b46b
110
+ d25bf5f0595bbe24655141438e7a100b
111
+ "
112
+ );
113
+
114
+ #[test]
115
+ fn round_trip() {
116
+ let signature = Signature::from_bytes(&SIGNATURE_BYTES);
117
+ let serialized = bincode::serialize(&signature).unwrap();
118
+ let deserialized = bincode::deserialize(&serialized).unwrap();
119
+ assert_eq!(signature, deserialized);
120
+ }
121
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pkcs8-v1.der ADDED
Binary file (48 Bytes). View file
 
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pkcs8-v1.pem ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ -----BEGIN PRIVATE KEY-----
2
+ MC4CAQAwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC
3
+ -----END PRIVATE KEY-----
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pkcs8-v2.der ADDED
Binary file (116 Bytes). View file
 
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pkcs8-v2.pem ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ -----BEGIN PRIVATE KEY-----
2
+ MHICAQEwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC
3
+ oB8wHQYKKoZIhvcNAQkJFDEPDA1DdXJkbGUgQ2hhaXJzgSEAGb9ECWmEzf6FQbrB
4
+ Z9w7lshQhqowtrbLDFw4rXAxZuE=
5
+ -----END PRIVATE KEY------
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pubkey.der ADDED
Binary file (44 Bytes). View file
 
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/examples/pubkey.pem ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ -----BEGIN PUBLIC KEY-----
2
+ MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE=
3
+ -----END PUBLIC KEY-----
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/hex.rs ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Hexadecimal display/serialization tests.
2
+
3
+ use ed25519::Signature;
4
+ use hex_literal::hex;
5
+ use std::str::FromStr;
6
+
7
+ /// Test 1 signature from RFC 8032 § 7.1
8
+ /// <https://datatracker.ietf.org/doc/html/rfc8032#section-7.1>
9
+ const TEST_1_SIGNATURE: [u8; Signature::BYTE_SIZE] = hex!(
10
+ "e5564300c360ac729086e2cc806e828a
11
+ 84877f1eb8e5d974d873e06522490155
12
+ 5fb8821590a33bacc61e39701cf9b46b
13
+ d25bf5f0595bbe24655141438e7a100b"
14
+ );
15
+
16
+ #[test]
17
+ fn display() {
18
+ let sig = Signature::from_bytes(&TEST_1_SIGNATURE);
19
+ assert_eq!(sig.to_string(), "E5564300C360AC729086E2CC806E828A84877F1EB8E5D974D873E065224901555FB8821590A33BACC61E39701CF9B46BD25BF5F0595BBE24655141438E7A100B")
20
+ }
21
+
22
+ #[test]
23
+ fn lower_hex() {
24
+ let sig = Signature::from_bytes(&TEST_1_SIGNATURE);
25
+ assert_eq!(format!("{:x}", sig), "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b")
26
+ }
27
+
28
+ #[test]
29
+ fn upper_hex() {
30
+ let sig = Signature::from_bytes(&TEST_1_SIGNATURE);
31
+ assert_eq!(format!("{:X}", sig), "E5564300C360AC729086E2CC806E828A84877F1EB8E5D974D873E065224901555FB8821590A33BACC61E39701CF9B46BD25BF5F0595BBE24655141438E7A100B")
32
+ }
33
+
34
+ #[test]
35
+ fn from_str_lower() {
36
+ let sig = Signature::from_str("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b").unwrap();
37
+ assert_eq!(sig.to_bytes(), TEST_1_SIGNATURE);
38
+ }
39
+
40
+ #[test]
41
+ fn from_str_upper() {
42
+ let sig = Signature::from_str("E5564300C360AC729086E2CC806E828A84877F1EB8E5D974D873E065224901555FB8821590A33BACC61E39701CF9B46BD25BF5F0595BBE24655141438E7A100B").unwrap();
43
+ assert_eq!(sig.to_bytes(), TEST_1_SIGNATURE);
44
+ }
45
+
46
+ #[test]
47
+ fn from_str_rejects_mixed_case() {
48
+ let result = Signature::from_str("E5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
49
+ assert!(result.is_err());
50
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/pkcs8.rs ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! PKCS#8 private key tests
2
+
3
+ #![cfg(feature = "pkcs8")]
4
+
5
+ use ed25519::pkcs8::{DecodePrivateKey, DecodePublicKey, KeypairBytes, PublicKeyBytes};
6
+ use hex_literal::hex;
7
+
8
+ #[cfg(feature = "alloc")]
9
+ use ed25519::pkcs8::{EncodePrivateKey, EncodePublicKey};
10
+
11
+ /// Ed25519 PKCS#8 v1 private key encoded as ASN.1 DER.
12
+ const PKCS8_V1_DER: &[u8] = include_bytes!("examples/pkcs8-v1.der");
13
+
14
+ /// Ed25519 PKCS#8 v2 private key + public key encoded as ASN.1 DER.
15
+ const PKCS8_V2_DER: &[u8] = include_bytes!("examples/pkcs8-v2.der");
16
+
17
+ /// Ed25519 SubjectPublicKeyInfo encoded as ASN.1 DER.
18
+ const PUBLIC_KEY_DER: &[u8] = include_bytes!("examples/pubkey.der");
19
+
20
+ #[test]
21
+ fn decode_pkcs8_v1() {
22
+ let keypair = KeypairBytes::from_pkcs8_der(PKCS8_V1_DER).unwrap();
23
+
24
+ // Extracted with:
25
+ // $ openssl asn1parse -inform der -in tests/examples/pkcs8-v1.der
26
+ assert_eq!(
27
+ keypair.secret_key,
28
+ &hex!("D4EE72DBF913584AD5B6D8F1F769F8AD3AFE7C28CBF1D4FBE097A88F44755842")[..]
29
+ );
30
+
31
+ assert_eq!(keypair.public_key, None);
32
+ }
33
+
34
+ #[test]
35
+ fn decode_pkcs8_v2() {
36
+ let keypair = KeypairBytes::from_pkcs8_der(PKCS8_V2_DER).unwrap();
37
+
38
+ // Extracted with:
39
+ // $ openssl asn1parse -inform der -in tests/examples/pkcs8-v2.der
40
+ assert_eq!(
41
+ keypair.secret_key,
42
+ &hex!("D4EE72DBF913584AD5B6D8F1F769F8AD3AFE7C28CBF1D4FBE097A88F44755842")[..]
43
+ );
44
+
45
+ assert_eq!(
46
+ keypair.public_key.unwrap().0,
47
+ hex!("19BF44096984CDFE8541BAC167DC3B96C85086AA30B6B6CB0C5C38AD703166E1")
48
+ );
49
+ }
50
+
51
+ #[test]
52
+ fn decode_public_key() {
53
+ let public_key = PublicKeyBytes::from_public_key_der(PUBLIC_KEY_DER).unwrap();
54
+
55
+ // Extracted with:
56
+ // $ openssl pkey -inform der -in tests/examples/pkcs8-v1.der -pubout -text
57
+ assert_eq!(
58
+ public_key.as_ref(),
59
+ &hex!("19BF44096984CDFE8541BAC167DC3B96C85086AA30B6B6CB0C5C38AD703166E1")
60
+ );
61
+ }
62
+
63
+ #[cfg(feature = "alloc")]
64
+ #[test]
65
+ fn encode_pkcs8_v1() {
66
+ let pk = KeypairBytes::from_pkcs8_der(PKCS8_V1_DER).unwrap();
67
+ let pk_der = pk.to_pkcs8_der().unwrap();
68
+ assert_eq!(pk_der.as_bytes(), PKCS8_V1_DER);
69
+ }
70
+
71
+ #[cfg(feature = "alloc")]
72
+ #[test]
73
+ fn encode_pkcs8_v2() {
74
+ let pk = KeypairBytes::from_pkcs8_der(PKCS8_V2_DER).unwrap();
75
+ let pk2 = KeypairBytes::from_pkcs8_der(pk.to_pkcs8_der().unwrap().as_bytes()).unwrap();
76
+ assert_eq!(pk.secret_key, pk2.secret_key);
77
+ assert_eq!(pk.public_key, pk2.public_key);
78
+ }
79
+
80
+ #[cfg(feature = "alloc")]
81
+ #[test]
82
+ fn encode_public_key() {
83
+ let pk = PublicKeyBytes::from_public_key_der(PUBLIC_KEY_DER).unwrap();
84
+ let pk_der = pk.to_public_key_der().unwrap();
85
+ assert_eq!(pk_der.as_ref(), PUBLIC_KEY_DER);
86
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/ed25519-2.2.3/tests/serde.rs ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Tests for serde serializers/deserializers
2
+
3
+ #![cfg(feature = "serde")]
4
+
5
+ use ed25519::{Signature, SignatureBytes};
6
+ use hex_literal::hex;
7
+
8
+ const EXAMPLE_SIGNATURE: SignatureBytes = hex!(
9
+ "3f3e3d3c3b3a393837363534333231302f2e2d2c2b2a29282726252423222120"
10
+ "1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100"
11
+ );
12
+
13
+ #[test]
14
+ fn test_serialize() {
15
+ let signature = Signature::try_from(&EXAMPLE_SIGNATURE[..]).unwrap();
16
+ dbg!(&signature);
17
+ let encoded_signature: Vec<u8> = bincode::serialize(&signature).unwrap();
18
+ assert_eq!(&EXAMPLE_SIGNATURE[..], &encoded_signature[..]);
19
+ }
20
+
21
+ #[test]
22
+ fn test_deserialize() {
23
+ let signature = bincode::deserialize::<Signature>(&EXAMPLE_SIGNATURE).unwrap();
24
+ assert_eq!(EXAMPLE_SIGNATURE, signature.to_bytes());
25
+ }
26
+
27
+ #[cfg(feature = "serde_bytes")]
28
+ #[test]
29
+ fn test_serialize_bytes() {
30
+ use bincode::Options;
31
+
32
+ let signature = Signature::try_from(&EXAMPLE_SIGNATURE[..]).unwrap();
33
+
34
+ let mut encoded_signature = Vec::new();
35
+ let options = bincode::DefaultOptions::new()
36
+ .with_fixint_encoding()
37
+ .allow_trailing_bytes();
38
+ let mut serializer = bincode::Serializer::new(&mut encoded_signature, options);
39
+ serde_bytes::serialize(&signature, &mut serializer).unwrap();
40
+
41
+ let mut expected = Vec::from(Signature::BYTE_SIZE.to_le_bytes());
42
+ expected.extend(&EXAMPLE_SIGNATURE[..]);
43
+ assert_eq!(&expected[..], &encoded_signature[..]);
44
+ }
45
+
46
+ #[cfg(feature = "serde_bytes")]
47
+ #[test]
48
+ fn test_deserialize_bytes() {
49
+ use bincode::Options;
50
+
51
+ let mut encoded_signature = Vec::from(Signature::BYTE_SIZE.to_le_bytes());
52
+ encoded_signature.extend(&EXAMPLE_SIGNATURE[..]);
53
+
54
+ let options = bincode::DefaultOptions::new()
55
+ .with_fixint_encoding()
56
+ .allow_trailing_bytes();
57
+ let mut deserializer = bincode::de::Deserializer::from_slice(&encoded_signature[..], options);
58
+
59
+ let signature: Signature = serde_bytes::deserialize(&mut deserializer).unwrap();
60
+
61
+ assert_eq!(EXAMPLE_SIGNATURE, signature.to_bytes());
62
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/env_logger-0.11.9/src/writer/mod.rs ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mod buffer;
2
+ mod target;
3
+
4
+ use std::{io, mem, sync::Mutex};
5
+
6
+ use buffer::BufferWriter;
7
+
8
+ pub(crate) use buffer::Buffer;
9
+
10
+ pub use target::Target;
11
+
12
+ /// Whether or not to print styles to the target.
13
+ #[allow(clippy::exhaustive_enums)] // By definition don't need more
14
+ #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Default)]
15
+ pub enum WriteStyle {
16
+ /// Try to print styles, but don't force the issue.
17
+ #[default]
18
+ Auto,
19
+ /// Try very hard to print styles.
20
+ Always,
21
+ /// Never print styles.
22
+ Never,
23
+ }
24
+
25
+ #[cfg(feature = "color")]
26
+ impl From<anstream::ColorChoice> for WriteStyle {
27
+ fn from(choice: anstream::ColorChoice) -> Self {
28
+ match choice {
29
+ anstream::ColorChoice::Auto => Self::Auto,
30
+ anstream::ColorChoice::Always => Self::Always,
31
+ anstream::ColorChoice::AlwaysAnsi => Self::Always,
32
+ anstream::ColorChoice::Never => Self::Never,
33
+ }
34
+ }
35
+ }
36
+
37
+ #[cfg(feature = "color")]
38
+ impl From<WriteStyle> for anstream::ColorChoice {
39
+ fn from(choice: WriteStyle) -> Self {
40
+ match choice {
41
+ WriteStyle::Auto => anstream::ColorChoice::Auto,
42
+ WriteStyle::Always => anstream::ColorChoice::Always,
43
+ WriteStyle::Never => anstream::ColorChoice::Never,
44
+ }
45
+ }
46
+ }
47
+
48
+ /// A terminal target with color awareness.
49
+ #[derive(Debug)]
50
+ pub(crate) struct Writer {
51
+ inner: BufferWriter,
52
+ }
53
+
54
+ impl Writer {
55
+ pub(crate) fn write_style(&self) -> WriteStyle {
56
+ self.inner.write_style()
57
+ }
58
+
59
+ pub(crate) fn buffer(&self) -> Buffer {
60
+ self.inner.buffer()
61
+ }
62
+
63
+ pub(crate) fn print(&self, buf: &Buffer) -> io::Result<()> {
64
+ self.inner.print(buf)
65
+ }
66
+ }
67
+
68
+ /// A builder for a terminal writer.
69
+ ///
70
+ /// The target and style choice can be configured before building.
71
+ #[derive(Debug)]
72
+ pub(crate) struct Builder {
73
+ target: Target,
74
+ write_style: WriteStyle,
75
+ is_test: bool,
76
+ built: bool,
77
+ }
78
+
79
+ impl Builder {
80
+ /// Initialize the writer builder with defaults.
81
+ pub(crate) fn new() -> Self {
82
+ Builder {
83
+ target: Default::default(),
84
+ write_style: Default::default(),
85
+ is_test: false,
86
+ built: false,
87
+ }
88
+ }
89
+
90
+ /// Set the target to write to.
91
+ pub(crate) fn target(&mut self, target: Target) -> &mut Self {
92
+ self.target = target;
93
+ self
94
+ }
95
+
96
+ /// Parses a style choice string.
97
+ ///
98
+ /// See the [Disabling colors] section for more details.
99
+ ///
100
+ /// [Disabling colors]: ../index.html#disabling-colors
101
+ pub(crate) fn parse_write_style(&mut self, write_style: &str) -> &mut Self {
102
+ self.write_style(parse_write_style(write_style))
103
+ }
104
+
105
+ /// Whether or not to print style characters when writing.
106
+ pub(crate) fn write_style(&mut self, write_style: WriteStyle) -> &mut Self {
107
+ self.write_style = write_style;
108
+ self
109
+ }
110
+
111
+ /// Whether or not to capture logs for `cargo test`.
112
+ #[allow(clippy::wrong_self_convention)]
113
+ pub(crate) fn is_test(&mut self, is_test: bool) -> &mut Self {
114
+ self.is_test = is_test;
115
+ self
116
+ }
117
+
118
+ /// Build a terminal writer.
119
+ pub(crate) fn build(&mut self) -> Writer {
120
+ assert!(!self.built, "attempt to re-use consumed builder");
121
+ self.built = true;
122
+
123
+ let color_choice = self.write_style;
124
+ #[cfg(feature = "auto-color")]
125
+ let color_choice = if color_choice == WriteStyle::Auto {
126
+ match &self.target {
127
+ Target::Stdout => anstream::AutoStream::choice(&io::stdout()).into(),
128
+ Target::Stderr => anstream::AutoStream::choice(&io::stderr()).into(),
129
+ Target::Pipe(_) => color_choice,
130
+ }
131
+ } else {
132
+ color_choice
133
+ };
134
+ let color_choice = if color_choice == WriteStyle::Auto {
135
+ WriteStyle::Never
136
+ } else {
137
+ color_choice
138
+ };
139
+
140
+ let writer = match mem::take(&mut self.target) {
141
+ Target::Stdout => BufferWriter::stdout(self.is_test, color_choice),
142
+ Target::Stderr => BufferWriter::stderr(self.is_test, color_choice),
143
+ Target::Pipe(pipe) => BufferWriter::pipe(Box::new(Mutex::new(pipe)), color_choice),
144
+ };
145
+
146
+ Writer { inner: writer }
147
+ }
148
+ }
149
+
150
+ impl Default for Builder {
151
+ fn default() -> Self {
152
+ Builder::new()
153
+ }
154
+ }
155
+
156
+ fn parse_write_style(spec: &str) -> WriteStyle {
157
+ match spec {
158
+ "auto" => WriteStyle::Auto,
159
+ "always" => WriteStyle::Always,
160
+ "never" => WriteStyle::Never,
161
+ _ => Default::default(),
162
+ }
163
+ }
164
+
165
+ #[cfg(test)]
166
+ mod tests {
167
+ use super::*;
168
+
169
+ #[test]
170
+ fn parse_write_style_valid() {
171
+ let inputs = vec![
172
+ ("auto", WriteStyle::Auto),
173
+ ("always", WriteStyle::Always),
174
+ ("never", WriteStyle::Never),
175
+ ];
176
+
177
+ for (input, expected) in inputs {
178
+ assert_eq!(expected, parse_write_style(input));
179
+ }
180
+ }
181
+
182
+ #[test]
183
+ fn parse_write_style_invalid() {
184
+ let inputs = vec!["", "true", "false", "NEVER!!"];
185
+
186
+ for input in inputs {
187
+ assert_eq!(WriteStyle::Auto, parse_write_style(input));
188
+ }
189
+ }
190
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/env_logger-0.11.9/src/writer/target.rs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// Log target, either `stdout`, `stderr` or a custom pipe.
2
+ #[non_exhaustive]
3
+ #[derive(Default)]
4
+ pub enum Target {
5
+ /// Logs will be sent to standard output.
6
+ Stdout,
7
+ /// Logs will be sent to standard error.
8
+ #[default]
9
+ Stderr,
10
+ /// Logs will be sent to a custom pipe.
11
+ Pipe(Box<dyn std::io::Write + Send + 'static>),
12
+ }
13
+
14
+ impl std::fmt::Debug for Target {
15
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16
+ write!(
17
+ f,
18
+ "{}",
19
+ match self {
20
+ Self::Stdout => "stdout",
21
+ Self::Stderr => "stderr",
22
+ Self::Pipe(_) => "pipe",
23
+ }
24
+ )
25
+ }
26
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/date.rs ADDED
The diff for this file is too large to render. See raw diff
 
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/datetime.rs ADDED
The diff for this file is too large to render. See raw diff
 
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/iso_week_date.rs ADDED
@@ -0,0 +1,919 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::{
2
+ civil::{Date, DateTime, Weekday},
3
+ error::Error,
4
+ fmt::temporal::{DEFAULT_DATETIME_PARSER, DEFAULT_DATETIME_PRINTER},
5
+ util::b,
6
+ Zoned,
7
+ };
8
+
9
+ /// A type representing an [ISO 8601 week date].
10
+ ///
11
+ /// The ISO 8601 week date scheme devises a calendar where days are identified
12
+ /// by their year, week number and weekday. All years have either precisely
13
+ /// 52 or 53 weeks.
14
+ ///
15
+ /// The first week of an ISO 8601 year corresponds to the week containing the
16
+ /// first Thursday of the year. For this reason, an ISO 8601 week year can be
17
+ /// mismatched with the day's corresponding Gregorian year. For example, the
18
+ /// ISO 8601 week date for `1995-01-01` is `1994-W52-7` (with `7` corresponding
19
+ /// to Sunday).
20
+ ///
21
+ /// ISO 8601 also considers Monday to be the start of the week, and uses
22
+ /// a 1-based numbering system. That is, Monday corresponds to `1` while
23
+ /// Sunday corresponds to `7` and is the last day of the week. Weekdays are
24
+ /// encapsulated by the [`Weekday`] type, which provides routines for easily
25
+ /// converting between different schemes (such as weeks where Sunday is the
26
+ /// beginning).
27
+ ///
28
+ /// [ISO 8601 week date]: https://en.wikipedia.org/wiki/ISO_week_date
29
+ ///
30
+ /// # Use case
31
+ ///
32
+ /// Some domains use this method of timekeeping. Otherwise, unless you
33
+ /// specifically want a week oriented calendar, it's likely that you'll never
34
+ /// need to care about this type.
35
+ ///
36
+ /// # Parsing and printing
37
+ ///
38
+ /// The `ISOWeekDate` type provides convenient trait implementations of
39
+ /// [`std::str::FromStr`] and [`std::fmt::Display`]. These use the format
40
+ /// specified by ISO 8601 for week dates:
41
+ ///
42
+ /// ```
43
+ /// use jiff::civil::ISOWeekDate;
44
+ ///
45
+ /// let week_date: ISOWeekDate = "2024-W24-7".parse()?;
46
+ /// assert_eq!(week_date.to_string(), "2024-W24-7");
47
+ /// assert_eq!(week_date.date().to_string(), "2024-06-16");
48
+ ///
49
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
50
+ /// ```
51
+ ///
52
+ /// ISO 8601 allows the `-` separator to be absent:
53
+ ///
54
+ /// ```
55
+ /// use jiff::civil::ISOWeekDate;
56
+ ///
57
+ /// let week_date: ISOWeekDate = "2024W241".parse()?;
58
+ /// assert_eq!(week_date.to_string(), "2024-W24-1");
59
+ /// assert_eq!(week_date.date().to_string(), "2024-06-10");
60
+ ///
61
+ /// // But you cannot mix and match. Either `-` separates
62
+ /// // both the year and week, or neither.
63
+ /// assert!("2024W24-1".parse::<ISOWeekDate>().is_err());
64
+ /// assert!("2024-W241".parse::<ISOWeekDate>().is_err());
65
+ ///
66
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
67
+ /// ```
68
+ ///
69
+ /// And the `W` may also be lowercase:
70
+ ///
71
+ /// ```
72
+ /// use jiff::civil::ISOWeekDate;
73
+ ///
74
+ /// let week_date: ISOWeekDate = "2024-w24-2".parse()?;
75
+ /// assert_eq!(week_date.to_string(), "2024-W24-2");
76
+ /// assert_eq!(week_date.date().to_string(), "2024-06-11");
77
+ ///
78
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
79
+ /// ```
80
+ ///
81
+ /// # Default value
82
+ ///
83
+ /// For convenience, this type implements the `Default` trait. Its default
84
+ /// value is the first day of the zeroth year. i.e., `0000-W1-1`.
85
+ ///
86
+ /// # Example: sample dates
87
+ ///
88
+ /// This example shows a couple ISO 8601 week dates and their corresponding
89
+ /// Gregorian equivalents:
90
+ ///
91
+ /// ```
92
+ /// use jiff::civil::{ISOWeekDate, Weekday, date};
93
+ ///
94
+ /// let d = date(2019, 12, 30);
95
+ /// let weekdate = ISOWeekDate::new(2020, 1, Weekday::Monday).unwrap();
96
+ /// assert_eq!(d.iso_week_date(), weekdate);
97
+ ///
98
+ /// let d = date(2024, 3, 9);
99
+ /// let weekdate = ISOWeekDate::new(2024, 10, Weekday::Saturday).unwrap();
100
+ /// assert_eq!(d.iso_week_date(), weekdate);
101
+ /// ```
102
+ ///
103
+ /// # Example: overlapping leap and long years
104
+ ///
105
+ /// A "long" ISO 8601 week year is a year with 53 weeks. That is, it is a year
106
+ /// that includes a leap week. This example shows all years in the 20th
107
+ /// century that are both Gregorian leap years and long years.
108
+ ///
109
+ /// ```
110
+ /// use jiff::civil::date;
111
+ ///
112
+ /// let mut overlapping = vec![];
113
+ /// for year in 1900..=1999 {
114
+ /// let date = date(year, 1, 1);
115
+ /// if date.in_leap_year() && date.iso_week_date().in_long_year() {
116
+ /// overlapping.push(year);
117
+ /// }
118
+ /// }
119
+ /// assert_eq!(overlapping, vec![
120
+ /// 1904, 1908, 1920, 1932, 1936, 1948, 1960, 1964, 1976, 1988, 1992,
121
+ /// ]);
122
+ /// ```
123
+ ///
124
+ /// # Example: printing all weeks in a year
125
+ ///
126
+ /// The ISO 8601 week calendar can be useful when you want to categorize
127
+ /// things into buckets of weeks where all weeks are exactly 7 days, _and_
128
+ /// you don't care as much about the precise Gregorian year. Here's an example
129
+ /// that prints all of the ISO 8601 weeks in one ISO 8601 week year:
130
+ ///
131
+ /// ```
132
+ /// use jiff::{civil::{ISOWeekDate, Weekday}, ToSpan};
133
+ ///
134
+ /// let target_year = 2024;
135
+ /// let iso_week_date = ISOWeekDate::new(target_year, 1, Weekday::Monday)?;
136
+ /// // Create a series of dates via the Gregorian calendar. But since a
137
+ /// // Gregorian week and an ISO 8601 week calendar week are both 7 days,
138
+ /// // this works fine.
139
+ /// let weeks = iso_week_date
140
+ /// .date()
141
+ /// .series(1.week())
142
+ /// .map(|d| d.iso_week_date())
143
+ /// .take_while(|wd| wd.year() == target_year);
144
+ /// for start_of_week in weeks {
145
+ /// let end_of_week = start_of_week.last_of_week()?;
146
+ /// println!(
147
+ /// "ISO week {}: {} - {}",
148
+ /// start_of_week.week(),
149
+ /// start_of_week.date(),
150
+ /// end_of_week.date()
151
+ /// );
152
+ /// }
153
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
154
+ /// ```
155
+ #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
156
+ pub struct ISOWeekDate {
157
+ year: i16,
158
+ week: i8,
159
+ weekday: Weekday,
160
+ }
161
+
162
+ impl ISOWeekDate {
163
+ /// The maximum representable ISO week date.
164
+ ///
165
+ /// The maximum corresponds to the ISO week date of the maximum [`Date`]
166
+ /// value. That is, `-9999-01-01`.
167
+ pub const MIN: ISOWeekDate = ISOWeekDate {
168
+ year: b::ISOYear::MIN,
169
+ week: b::ISOWeek::MIN,
170
+ weekday: Weekday::Monday,
171
+ };
172
+
173
+ /// The minimum representable ISO week date.
174
+ ///
175
+ /// The minimum corresponds to the ISO week date of the minimum [`Date`]
176
+ /// value. That is, `9999-12-31`.
177
+ pub const MAX: ISOWeekDate = ISOWeekDate {
178
+ year: b::ISOYear::MAX,
179
+ // Technical max is 52, but 9999 is not a leap year.
180
+ week: 52,
181
+ weekday: Weekday::Friday,
182
+ };
183
+
184
+ /// The first day of the zeroth year.
185
+ ///
186
+ /// This is guaranteed to be equivalent to `ISOWeekDate::default()`. Note
187
+ /// that this is not equivalent to `Date::default()`.
188
+ ///
189
+ /// # Example
190
+ ///
191
+ /// ```
192
+ /// use jiff::civil::{ISOWeekDate, date};
193
+ ///
194
+ /// assert_eq!(ISOWeekDate::ZERO, ISOWeekDate::default());
195
+ /// // The first day of the 0th year in the ISO week calendar is actually
196
+ /// // the third day of the 0th year in the proleptic Gregorian calendar!
197
+ /// assert_eq!(ISOWeekDate::default().date(), date(0, 1, 3));
198
+ /// ```
199
+ pub const ZERO: ISOWeekDate =
200
+ ISOWeekDate { year: 0, week: 1, weekday: Weekday::Monday };
201
+
202
+ /// Create a new ISO week date from it constituent parts.
203
+ ///
204
+ /// If the given values are out of range (based on what is representable
205
+ /// as a [`Date`]), then this returns an error. This will also return an
206
+ /// error if a leap week is given (week number `53`) for a year that does
207
+ /// not contain a leap week.
208
+ ///
209
+ /// # Example
210
+ ///
211
+ /// This example shows some the boundary conditions involving minimum
212
+ /// and maximum dates:
213
+ ///
214
+ /// ```
215
+ /// use jiff::civil::{ISOWeekDate, Weekday, date};
216
+ ///
217
+ /// // The year 1949 does not contain a leap week.
218
+ /// assert!(ISOWeekDate::new(1949, 53, Weekday::Monday).is_err());
219
+ ///
220
+ /// // Examples of dates at or exceeding the maximum.
221
+ /// let max = ISOWeekDate::new(9999, 52, Weekday::Friday).unwrap();
222
+ /// assert_eq!(max, ISOWeekDate::MAX);
223
+ /// assert_eq!(max.date(), date(9999, 12, 31));
224
+ /// assert!(ISOWeekDate::new(9999, 52, Weekday::Saturday).is_err());
225
+ /// assert!(ISOWeekDate::new(9999, 53, Weekday::Monday).is_err());
226
+ ///
227
+ /// // Examples of dates at or exceeding the minimum.
228
+ /// let min = ISOWeekDate::new(-9999, 1, Weekday::Monday).unwrap();
229
+ /// assert_eq!(min, ISOWeekDate::MIN);
230
+ /// assert_eq!(min.date(), date(-9999, 1, 1));
231
+ /// assert!(ISOWeekDate::new(-10000, 52, Weekday::Sunday).is_err());
232
+ /// ```
233
+ #[inline]
234
+ pub fn new(
235
+ year: i16,
236
+ week: i8,
237
+ weekday: Weekday,
238
+ ) -> Result<ISOWeekDate, Error> {
239
+ let year = b::ISOYear::check(year)?;
240
+ let week = b::ISOWeek::check(week)?;
241
+
242
+ // All combinations of years, weeks and weekdays allowed by our
243
+ // range types are valid ISO week dates with one exception: a week
244
+ // number of 53 is only valid for "long" years. Or years with an ISO
245
+ // leap week. It turns out this only happens when the last day of the
246
+ // year is a Thursday.
247
+ //
248
+ // Note that if the ranges in this crate are changed, this could be
249
+ // a little trickier if the range of ISOYear is different from Year.
250
+ debug_assert_eq!(b::Year::MIN, b::ISOYear::MIN);
251
+ debug_assert_eq!(b::Year::MAX, b::ISOYear::MAX);
252
+ if week == 53 && !is_long_year(year) {
253
+ return Err(b::ISOWeek::error().into());
254
+ }
255
+ // And also, the maximum Date constrains what we can utter with
256
+ // ISOWeekDate so that we can preserve infallible conversions between
257
+ // them. So since 9999-12-31 maps to 9999 W52 Friday, it follows that
258
+ // Saturday and Sunday are not allowed when the year is at the maximum
259
+ // value. So reject them.
260
+ //
261
+ // We don't need to worry about the minimum because the minimum date
262
+ // (-9999-01-01) corresponds also to the minimum possible combination
263
+ // of an ISO week date's fields: -9999 W01 Monday. Nice.
264
+ if year == b::ISOYear::MAX
265
+ && week == 52
266
+ && weekday.to_monday_zero_offset()
267
+ > Weekday::Friday.to_monday_zero_offset()
268
+ {
269
+ return Err(b::WeekdayMondayOne::error().into());
270
+ }
271
+ Ok(ISOWeekDate { year, week, weekday })
272
+ }
273
+
274
+ /// Like `ISOWeekDate::new`, but constrains out-of-bounds values
275
+ /// to their closest valid equivalent.
276
+ ///
277
+ /// For example, given `9999 W52 Saturday`, this will return
278
+ /// `9999 W52 Friday`.
279
+ #[cfg(test)]
280
+ #[inline]
281
+ fn new_constrain(
282
+ year: i16,
283
+ mut week: i8,
284
+ mut weekday: Weekday,
285
+ ) -> ISOWeekDate {
286
+ debug_assert_eq!(b::Year::MIN, b::ISOYear::MIN);
287
+ debug_assert_eq!(b::Year::MAX, b::ISOYear::MAX);
288
+ if week == 53 && !is_long_year(year) {
289
+ week = 52;
290
+ }
291
+ if year == b::ISOYear::MAX
292
+ && week == 52
293
+ && weekday.to_monday_zero_offset()
294
+ > Weekday::Friday.to_monday_zero_offset()
295
+ {
296
+ weekday = Weekday::Friday;
297
+ }
298
+ ISOWeekDate { year, week, weekday }
299
+ }
300
+
301
+ /// Converts a Gregorian date to an ISO week date.
302
+ ///
303
+ /// The minimum and maximum allowed values of an ISO week date are
304
+ /// set based on the minimum and maximum values of a `Date`. Therefore,
305
+ /// converting to and from `Date` values is non-lossy and infallible.
306
+ ///
307
+ /// This routine is equivalent to [`Date::iso_week_date`]. This routine
308
+ /// is also available via a `From<Date>` trait implementation for
309
+ /// `ISOWeekDate`.
310
+ ///
311
+ /// # Example
312
+ ///
313
+ /// ```
314
+ /// use jiff::civil::{ISOWeekDate, Weekday, date};
315
+ ///
316
+ /// let weekdate = ISOWeekDate::from_date(date(1948, 2, 10));
317
+ /// assert_eq!(
318
+ /// weekdate,
319
+ /// ISOWeekDate::new(1948, 7, Weekday::Tuesday).unwrap(),
320
+ /// );
321
+ /// ```
322
+ #[inline]
323
+ pub fn from_date(date: Date) -> ISOWeekDate {
324
+ date.iso_week_date()
325
+ }
326
+
327
+ // N.B. I tried defining a `ISOWeekDate::constant` for defining ISO week
328
+ // dates as constants, but it was too annoying to do. We could do it if
329
+ // there was a compelling reason for it though.
330
+
331
+ /// Returns the year component of this ISO 8601 week date.
332
+ ///
333
+ /// The value returned is guaranteed to be in the range `-9999..=9999`.
334
+ ///
335
+ /// # Example
336
+ ///
337
+ /// ```
338
+ /// use jiff::civil::date;
339
+ ///
340
+ /// let weekdate = date(2019, 12, 30).iso_week_date();
341
+ /// assert_eq!(weekdate.year(), 2020);
342
+ /// ```
343
+ #[inline]
344
+ pub fn year(self) -> i16 {
345
+ self.year
346
+ }
347
+
348
+ /// Returns the week component of this ISO 8601 week date.
349
+ ///
350
+ /// The value returned is guaranteed to be in the range `1..=53`. A
351
+ /// value of `53` can only occur for "long" years. That is, years
352
+ /// with a leap week. This occurs precisely in cases for which
353
+ /// [`ISOWeekDate::in_long_year`] returns `true`.
354
+ ///
355
+ /// # Example
356
+ ///
357
+ /// ```
358
+ /// use jiff::civil::date;
359
+ ///
360
+ /// let weekdate = date(2019, 12, 30).iso_week_date();
361
+ /// assert_eq!(weekdate.year(), 2020);
362
+ /// assert_eq!(weekdate.week(), 1);
363
+ ///
364
+ /// let weekdate = date(1948, 12, 31).iso_week_date();
365
+ /// assert_eq!(weekdate.year(), 1948);
366
+ /// assert_eq!(weekdate.week(), 53);
367
+ /// ```
368
+ #[inline]
369
+ pub fn week(self) -> i8 {
370
+ self.week
371
+ }
372
+
373
+ /// Returns the day component of this ISO 8601 week date.
374
+ ///
375
+ /// One can use methods on `Weekday` such as
376
+ /// [`Weekday::to_monday_one_offset`]
377
+ /// and
378
+ /// [`Weekday::to_sunday_zero_offset`]
379
+ /// to convert the weekday to a number.
380
+ ///
381
+ /// # Example
382
+ ///
383
+ /// ```
384
+ /// use jiff::civil::{date, Weekday};
385
+ ///
386
+ /// let weekdate = date(1948, 12, 31).iso_week_date();
387
+ /// assert_eq!(weekdate.year(), 1948);
388
+ /// assert_eq!(weekdate.week(), 53);
389
+ /// assert_eq!(weekdate.weekday(), Weekday::Friday);
390
+ /// assert_eq!(weekdate.weekday().to_monday_zero_offset(), 4);
391
+ /// assert_eq!(weekdate.weekday().to_monday_one_offset(), 5);
392
+ /// assert_eq!(weekdate.weekday().to_sunday_zero_offset(), 5);
393
+ /// assert_eq!(weekdate.weekday().to_sunday_one_offset(), 6);
394
+ /// ```
395
+ #[inline]
396
+ pub fn weekday(self) -> Weekday {
397
+ self.weekday
398
+ }
399
+
400
+ /// Returns the ISO 8601 week date corresponding to the first day in the
401
+ /// week of this week date. The date returned is guaranteed to have a
402
+ /// weekday of [`Weekday::Monday`].
403
+ ///
404
+ /// # Errors
405
+ ///
406
+ /// Since `-9999-01-01` falls on a Monday, it follows that the minimum
407
+ /// support Gregorian date is exactly equivalent to the minimum supported
408
+ /// ISO 8601 week date. This means that this routine can never actually
409
+ /// fail, but only insomuch as the minimums line up. For that reason, and
410
+ /// for consistency with [`ISOWeekDate::last_of_week`], the API is
411
+ /// fallible.
412
+ ///
413
+ /// # Example
414
+ ///
415
+ /// ```
416
+ /// use jiff::civil::{ISOWeekDate, Weekday, date};
417
+ ///
418
+ /// let wd = ISOWeekDate::new(2025, 5, Weekday::Wednesday).unwrap();
419
+ /// assert_eq!(wd.date(), date(2025, 1, 29));
420
+ /// assert_eq!(
421
+ /// wd.first_of_week()?,
422
+ /// ISOWeekDate::new(2025, 5, Weekday::Monday).unwrap(),
423
+ /// );
424
+ ///
425
+ /// // Works even for the minimum date.
426
+ /// assert_eq!(
427
+ /// ISOWeekDate::MIN.first_of_week()?,
428
+ /// ISOWeekDate::new(-9999, 1, Weekday::Monday).unwrap(),
429
+ /// );
430
+ ///
431
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
432
+ /// ```
433
+ #[inline]
434
+ pub fn first_of_week(self) -> Result<ISOWeekDate, Error> {
435
+ // I believe this can never return an error because `Monday` is in
436
+ // bounds for all possible year-and-week combinations. This is *only*
437
+ // because -9999-01-01 corresponds to -9999-W01-Monday. Which is kinda
438
+ // lucky. And I guess if we ever change the ranges, this could become
439
+ // fallible.
440
+ ISOWeekDate::new(self.year(), self.week(), Weekday::Monday)
441
+ }
442
+
443
+ /// Returns the ISO 8601 week date corresponding to the last day in the
444
+ /// week of this week date. The date returned is guaranteed to have a
445
+ /// weekday of [`Weekday::Sunday`].
446
+ ///
447
+ /// # Errors
448
+ ///
449
+ /// This can return an error if the last day of the week exceeds Jiff's
450
+ /// maximum Gregorian date of `9999-12-31`. It turns out this can happen
451
+ /// since `9999-12-31` falls on a Friday.
452
+ ///
453
+ /// # Example
454
+ ///
455
+ /// ```
456
+ /// use jiff::civil::{ISOWeekDate, Weekday, date};
457
+ ///
458
+ /// let wd = ISOWeekDate::new(2025, 5, Weekday::Wednesday).unwrap();
459
+ /// assert_eq!(wd.date(), date(2025, 1, 29));
460
+ /// assert_eq!(
461
+ /// wd.last_of_week()?,
462
+ /// ISOWeekDate::new(2025, 5, Weekday::Sunday).unwrap(),
463
+ /// );
464
+ ///
465
+ /// // Unlike `first_of_week`, this routine can actually fail on real
466
+ /// // values, although, only when close to the maximum supported date.
467
+ /// assert_eq!(
468
+ /// ISOWeekDate::MAX.last_of_week().unwrap_err().to_string(),
469
+ /// "parameter 'weekday (Monday 1-indexed)' \
470
+ /// is not in the required range of 1..=7",
471
+ /// );
472
+ ///
473
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
474
+ /// ```
475
+ #[inline]
476
+ pub fn last_of_week(self) -> Result<ISOWeekDate, Error> {
477
+ // This can return an error when in the last week of the maximum year
478
+ // supported by Jiff. That's because the Saturday and Sunday of that
479
+ // week are actually in Gregorian year 10,000.
480
+ ISOWeekDate::new(self.year(), self.week(), Weekday::Sunday)
481
+ }
482
+
483
+ /// Returns the ISO 8601 week date corresponding to the first day in the
484
+ /// year of this week date. The date returned is guaranteed to have a
485
+ /// weekday of [`Weekday::Monday`].
486
+ ///
487
+ /// # Errors
488
+ ///
489
+ /// Since `-9999-01-01` falls on a Monday, it follows that the minimum
490
+ /// support Gregorian date is exactly equivalent to the minimum supported
491
+ /// ISO 8601 week date. This means that this routine can never actually
492
+ /// fail, but only insomuch as the minimums line up. For that reason, and
493
+ /// for consistency with [`ISOWeekDate::last_of_year`], the API is
494
+ /// fallible.
495
+ ///
496
+ /// # Example
497
+ ///
498
+ /// ```
499
+ /// use jiff::civil::{ISOWeekDate, Weekday, date};
500
+ ///
501
+ /// let wd = ISOWeekDate::new(2025, 5, Weekday::Wednesday).unwrap();
502
+ /// assert_eq!(wd.date(), date(2025, 1, 29));
503
+ /// assert_eq!(
504
+ /// wd.first_of_year()?,
505
+ /// ISOWeekDate::new(2025, 1, Weekday::Monday).unwrap(),
506
+ /// );
507
+ ///
508
+ /// // Works even for the minimum date.
509
+ /// assert_eq!(
510
+ /// ISOWeekDate::MIN.first_of_year()?,
511
+ /// ISOWeekDate::new(-9999, 1, Weekday::Monday).unwrap(),
512
+ /// );
513
+ ///
514
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
515
+ /// ```
516
+ #[inline]
517
+ pub fn first_of_year(self) -> Result<ISOWeekDate, Error> {
518
+ // I believe this can never return an error because `Monday` is in
519
+ // bounds for all possible years. This is *only* because -9999-01-01
520
+ // corresponds to -9999-W01-Monday. Which is kinda lucky. And I guess
521
+ // if we ever change the ranges, this could become fallible.
522
+ ISOWeekDate::new(self.year(), 1, Weekday::Monday)
523
+ }
524
+
525
+ /// Returns the ISO 8601 week date corresponding to the last day in the
526
+ /// year of this week date. The date returned is guaranteed to have a
527
+ /// weekday of [`Weekday::Sunday`].
528
+ ///
529
+ /// # Errors
530
+ ///
531
+ /// This can return an error if the last day of the year exceeds Jiff's
532
+ /// maximum Gregorian date of `9999-12-31`. It turns out this can happen
533
+ /// since `9999-12-31` falls on a Friday.
534
+ ///
535
+ /// # Example
536
+ ///
537
+ /// ```
538
+ /// use jiff::civil::{ISOWeekDate, Weekday, date};
539
+ ///
540
+ /// let wd = ISOWeekDate::new(2025, 5, Weekday::Wednesday).unwrap();
541
+ /// assert_eq!(wd.date(), date(2025, 1, 29));
542
+ /// assert_eq!(
543
+ /// wd.last_of_year()?,
544
+ /// ISOWeekDate::new(2025, 52, Weekday::Sunday).unwrap(),
545
+ /// );
546
+ ///
547
+ /// // Works correctly for "long" years.
548
+ /// let wd = ISOWeekDate::new(2026, 5, Weekday::Wednesday).unwrap();
549
+ /// assert_eq!(wd.date(), date(2026, 1, 28));
550
+ /// assert_eq!(
551
+ /// wd.last_of_year()?,
552
+ /// ISOWeekDate::new(2026, 53, Weekday::Sunday).unwrap(),
553
+ /// );
554
+ ///
555
+ /// // Unlike `first_of_year`, this routine can actually fail on real
556
+ /// // values, although, only when close to the maximum supported date.
557
+ /// assert_eq!(
558
+ /// ISOWeekDate::MAX.last_of_year().unwrap_err().to_string(),
559
+ /// "parameter 'weekday (Monday 1-indexed)' \
560
+ /// is not in the required range of 1..=7",
561
+ /// );
562
+ ///
563
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
564
+ /// ```
565
+ #[inline]
566
+ pub fn last_of_year(self) -> Result<ISOWeekDate, Error> {
567
+ // This can return an error when in the maximum year supported by
568
+ // Jiff. That's because the last Saturday and Sunday of that year are
569
+ // actually in Gregorian year 10,000.
570
+ ISOWeekDate::new(self.year(), self.weeks_in_year(), Weekday::Sunday)
571
+ }
572
+
573
+ /// Returns the total number of days in the year of this ISO 8601 week
574
+ /// date.
575
+ ///
576
+ /// It is guaranteed that the value returned is either 364 or 371. The
577
+ /// latter case occurs precisely when [`ISOWeekDate::in_long_year`]
578
+ /// returns `true`.
579
+ ///
580
+ /// # Example
581
+ ///
582
+ /// ```
583
+ /// use jiff::civil::{ISOWeekDate, Weekday};
584
+ ///
585
+ /// let weekdate = ISOWeekDate::new(2025, 7, Weekday::Monday).unwrap();
586
+ /// assert_eq!(weekdate.days_in_year(), 364);
587
+ /// let weekdate = ISOWeekDate::new(2026, 7, Weekday::Monday).unwrap();
588
+ /// assert_eq!(weekdate.days_in_year(), 371);
589
+ /// ```
590
+ #[inline]
591
+ pub fn days_in_year(self) -> i16 {
592
+ if self.in_long_year() {
593
+ 371
594
+ } else {
595
+ 364
596
+ }
597
+ }
598
+
599
+ /// Returns the total number of weeks in the year of this ISO 8601 week
600
+ /// date.
601
+ ///
602
+ /// It is guaranteed that the value returned is either 52 or 53. The
603
+ /// latter case occurs precisely when [`ISOWeekDate::in_long_year`]
604
+ /// returns `true`.
605
+ ///
606
+ /// # Example
607
+ ///
608
+ /// ```
609
+ /// use jiff::civil::{ISOWeekDate, Weekday};
610
+ ///
611
+ /// let weekdate = ISOWeekDate::new(2025, 7, Weekday::Monday).unwrap();
612
+ /// assert_eq!(weekdate.weeks_in_year(), 52);
613
+ /// let weekdate = ISOWeekDate::new(2026, 7, Weekday::Monday).unwrap();
614
+ /// assert_eq!(weekdate.weeks_in_year(), 53);
615
+ /// ```
616
+ #[inline]
617
+ pub fn weeks_in_year(self) -> i8 {
618
+ if self.in_long_year() {
619
+ 53
620
+ } else {
621
+ 52
622
+ }
623
+ }
624
+
625
+ /// Returns true if and only if the year of this week date is a "long"
626
+ /// year.
627
+ ///
628
+ /// A long year is one that contains precisely 53 weeks. All other years
629
+ /// contain precisely 52 weeks.
630
+ ///
631
+ /// # Example
632
+ ///
633
+ /// ```
634
+ /// use jiff::civil::{ISOWeekDate, Weekday};
635
+ ///
636
+ /// let weekdate = ISOWeekDate::new(1948, 7, Weekday::Monday).unwrap();
637
+ /// assert!(weekdate.in_long_year());
638
+ /// let weekdate = ISOWeekDate::new(1949, 7, Weekday::Monday).unwrap();
639
+ /// assert!(!weekdate.in_long_year());
640
+ /// ```
641
+ #[inline]
642
+ pub fn in_long_year(self) -> bool {
643
+ is_long_year(self.year())
644
+ }
645
+
646
+ /// Returns the ISO 8601 date immediately following this one.
647
+ ///
648
+ /// # Errors
649
+ ///
650
+ /// This returns an error when this date is the maximum value.
651
+ ///
652
+ /// # Example
653
+ ///
654
+ /// ```
655
+ /// use jiff::civil::{ISOWeekDate, Weekday};
656
+ ///
657
+ /// let wd = ISOWeekDate::new(2025, 5, Weekday::Wednesday).unwrap();
658
+ /// assert_eq!(
659
+ /// wd.tomorrow()?,
660
+ /// ISOWeekDate::new(2025, 5, Weekday::Thursday).unwrap(),
661
+ /// );
662
+ ///
663
+ /// // The max doesn't have a tomorrow.
664
+ /// assert!(ISOWeekDate::MAX.tomorrow().is_err());
665
+ ///
666
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
667
+ /// ```
668
+ #[inline]
669
+ pub fn tomorrow(self) -> Result<ISOWeekDate, Error> {
670
+ // I suppose we could probably implement this in a more efficient
671
+ // manner but avoiding the roundtrip through Gregorian dates.
672
+ self.date().tomorrow().map(|d| d.iso_week_date())
673
+ }
674
+
675
+ /// Returns the ISO 8601 week date immediately preceding this one.
676
+ ///
677
+ /// # Errors
678
+ ///
679
+ /// This returns an error when this date is the minimum value.
680
+ ///
681
+ /// # Example
682
+ ///
683
+ /// ```
684
+ /// use jiff::civil::{ISOWeekDate, Weekday};
685
+ ///
686
+ /// let wd = ISOWeekDate::new(2025, 5, Weekday::Wednesday).unwrap();
687
+ /// assert_eq!(
688
+ /// wd.yesterday()?,
689
+ /// ISOWeekDate::new(2025, 5, Weekday::Tuesday).unwrap(),
690
+ /// );
691
+ ///
692
+ /// // The min doesn't have a yesterday.
693
+ /// assert!(ISOWeekDate::MIN.yesterday().is_err());
694
+ ///
695
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
696
+ /// ```
697
+ #[inline]
698
+ pub fn yesterday(self) -> Result<ISOWeekDate, Error> {
699
+ // I suppose we could probably implement this in a more efficient
700
+ // manner but avoiding the roundtrip through Gregorian dates.
701
+ self.date().yesterday().map(|d| d.iso_week_date())
702
+ }
703
+
704
+ /// Converts this ISO week date to a Gregorian [`Date`].
705
+ ///
706
+ /// The minimum and maximum allowed values of an ISO week date are
707
+ /// set based on the minimum and maximum values of a `Date`. Therefore,
708
+ /// converting to and from `Date` values is non-lossy and infallible.
709
+ ///
710
+ /// This routine is equivalent to [`Date::from_iso_week_date`].
711
+ ///
712
+ /// # Example
713
+ ///
714
+ /// ```
715
+ /// use jiff::civil::{ISOWeekDate, Weekday, date};
716
+ ///
717
+ /// let weekdate = ISOWeekDate::new(1948, 7, Weekday::Tuesday).unwrap();
718
+ /// assert_eq!(weekdate.date(), date(1948, 2, 10));
719
+ /// ```
720
+ #[inline]
721
+ pub fn date(self) -> Date {
722
+ Date::from_iso_week_date(self)
723
+ }
724
+ }
725
+
726
+ impl Default for ISOWeekDate {
727
+ fn default() -> ISOWeekDate {
728
+ ISOWeekDate::ZERO
729
+ }
730
+ }
731
+
732
+ impl core::fmt::Display for ISOWeekDate {
733
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
734
+ use crate::fmt::StdFmtWrite;
735
+
736
+ DEFAULT_DATETIME_PRINTER
737
+ .print_iso_week_date(self, StdFmtWrite(f))
738
+ .map_err(|_| core::fmt::Error)
739
+ }
740
+ }
741
+
742
+ impl core::str::FromStr for ISOWeekDate {
743
+ type Err = Error;
744
+
745
+ fn from_str(string: &str) -> Result<ISOWeekDate, Error> {
746
+ DEFAULT_DATETIME_PARSER.parse_iso_week_date(string)
747
+ }
748
+ }
749
+
750
+ impl Ord for ISOWeekDate {
751
+ #[inline]
752
+ fn cmp(&self, other: &ISOWeekDate) -> core::cmp::Ordering {
753
+ (self.year(), self.week(), self.weekday().to_monday_one_offset()).cmp(
754
+ &(
755
+ other.year(),
756
+ other.week(),
757
+ other.weekday().to_monday_one_offset(),
758
+ ),
759
+ )
760
+ }
761
+ }
762
+
763
+ impl PartialOrd for ISOWeekDate {
764
+ #[inline]
765
+ fn partial_cmp(&self, other: &ISOWeekDate) -> Option<core::cmp::Ordering> {
766
+ Some(self.cmp(other))
767
+ }
768
+ }
769
+
770
+ impl From<Date> for ISOWeekDate {
771
+ #[inline]
772
+ fn from(date: Date) -> ISOWeekDate {
773
+ ISOWeekDate::from_date(date)
774
+ }
775
+ }
776
+
777
+ impl From<DateTime> for ISOWeekDate {
778
+ #[inline]
779
+ fn from(dt: DateTime) -> ISOWeekDate {
780
+ ISOWeekDate::from(dt.date())
781
+ }
782
+ }
783
+
784
+ impl From<Zoned> for ISOWeekDate {
785
+ #[inline]
786
+ fn from(zdt: Zoned) -> ISOWeekDate {
787
+ ISOWeekDate::from(zdt.date())
788
+ }
789
+ }
790
+
791
+ impl<'a> From<&'a Zoned> for ISOWeekDate {
792
+ #[inline]
793
+ fn from(zdt: &'a Zoned) -> ISOWeekDate {
794
+ ISOWeekDate::from(zdt.date())
795
+ }
796
+ }
797
+
798
+ #[cfg(feature = "serde")]
799
+ impl serde_core::Serialize for ISOWeekDate {
800
+ #[inline]
801
+ fn serialize<S: serde_core::Serializer>(
802
+ &self,
803
+ serializer: S,
804
+ ) -> Result<S::Ok, S::Error> {
805
+ serializer.collect_str(self)
806
+ }
807
+ }
808
+
809
+ #[cfg(feature = "serde")]
810
+ impl<'de> serde_core::Deserialize<'de> for ISOWeekDate {
811
+ #[inline]
812
+ fn deserialize<D: serde_core::Deserializer<'de>>(
813
+ deserializer: D,
814
+ ) -> Result<ISOWeekDate, D::Error> {
815
+ use serde_core::de;
816
+
817
+ struct ISOWeekDateVisitor;
818
+
819
+ impl<'de> de::Visitor<'de> for ISOWeekDateVisitor {
820
+ type Value = ISOWeekDate;
821
+
822
+ fn expecting(
823
+ &self,
824
+ f: &mut core::fmt::Formatter,
825
+ ) -> core::fmt::Result {
826
+ f.write_str("an ISO 8601 week date string")
827
+ }
828
+
829
+ #[inline]
830
+ fn visit_bytes<E: de::Error>(
831
+ self,
832
+ value: &[u8],
833
+ ) -> Result<ISOWeekDate, E> {
834
+ DEFAULT_DATETIME_PARSER
835
+ .parse_iso_week_date(value)
836
+ .map_err(de::Error::custom)
837
+ }
838
+
839
+ #[inline]
840
+ fn visit_str<E: de::Error>(
841
+ self,
842
+ value: &str,
843
+ ) -> Result<ISOWeekDate, E> {
844
+ self.visit_bytes(value.as_bytes())
845
+ }
846
+ }
847
+
848
+ deserializer.deserialize_str(ISOWeekDateVisitor)
849
+ }
850
+ }
851
+
852
+ #[cfg(test)]
853
+ impl quickcheck::Arbitrary for ISOWeekDate {
854
+ fn arbitrary(g: &mut quickcheck::Gen) -> ISOWeekDate {
855
+ let year = b::ISOYear::arbitrary(g);
856
+ let week = b::ISOWeek::arbitrary(g);
857
+ let weekday = Weekday::arbitrary(g);
858
+ ISOWeekDate::new_constrain(year, week, weekday)
859
+ }
860
+
861
+ fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = ISOWeekDate>> {
862
+ alloc::boxed::Box::new(
863
+ (self.year(), self.week(), self.weekday()).shrink().map(
864
+ |(year, week, weekday)| {
865
+ ISOWeekDate::new_constrain(year, week, weekday)
866
+ },
867
+ ),
868
+ )
869
+ }
870
+ }
871
+
872
+ /// Returns true if the given ISO year is a "long" year or not.
873
+ ///
874
+ /// A "long" year is a year with 53 weeks. Otherwise, it's a "short" year
875
+ /// with 52 weeks.
876
+ fn is_long_year(year: i16) -> bool {
877
+ // Inspired by: https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year
878
+ let last =
879
+ Date::new(year, 12, 31).expect("last day of year is always valid");
880
+ let weekday = last.weekday();
881
+ weekday == Weekday::Thursday
882
+ || (last.in_leap_year() && weekday == Weekday::Friday)
883
+ }
884
+
885
+ #[cfg(not(miri))]
886
+ #[cfg(test)]
887
+ mod tests {
888
+ use super::*;
889
+
890
+ quickcheck::quickcheck! {
891
+ fn prop_all_long_years_have_53rd_week(year: i16) -> quickcheck::TestResult {
892
+ if b::Year::check(year).is_err() {
893
+ return quickcheck::TestResult::discard();
894
+ }
895
+ quickcheck::TestResult::from_bool(!is_long_year(year)
896
+ || ISOWeekDate::new(year, 53, Weekday::Sunday).is_ok())
897
+ }
898
+
899
+ fn prop_prev_day_is_less(wd: ISOWeekDate) -> quickcheck::TestResult {
900
+ use crate::ToSpan;
901
+
902
+ if wd == ISOWeekDate::MIN {
903
+ return quickcheck::TestResult::discard();
904
+ }
905
+ let prev_date = wd.date().checked_add(-1.days()).unwrap();
906
+ quickcheck::TestResult::from_bool(prev_date.iso_week_date() < wd)
907
+ }
908
+
909
+ fn prop_next_day_is_greater(wd: ISOWeekDate) -> quickcheck::TestResult {
910
+ use crate::ToSpan;
911
+
912
+ if wd == ISOWeekDate::MAX {
913
+ return quickcheck::TestResult::discard();
914
+ }
915
+ let next_date = wd.date().checked_add(1.days()).unwrap();
916
+ quickcheck::TestResult::from_bool(wd < next_date.iso_week_date())
917
+ }
918
+ }
919
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/mod.rs ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ Facilities for dealing with inexact dates and times.
3
+
4
+ # Overview
5
+
6
+ The essential types in this module are:
7
+
8
+ * [`Date`] is a specific day in the Gregorian calendar.
9
+ * [`Time`] is a specific wall clock time.
10
+ * [`DateTime`] is a combination of a day and a time.
11
+
12
+ Moreover, the [`date`](date()) and [`time`](time()) free functions can be used
13
+ to conveniently create values of any of three types above:
14
+
15
+ ```
16
+ use jiff::civil::{date, time};
17
+
18
+ assert_eq!(date(2024, 7, 31).to_string(), "2024-07-31");
19
+ assert_eq!(time(15, 20, 0, 123).to_string(), "15:20:00.000000123");
20
+ assert_eq!(
21
+ date(2024, 7, 31).at(15, 20, 0, 123).to_string(),
22
+ "2024-07-31T15:20:00.000000123",
23
+ );
24
+ assert_eq!(
25
+ time(15, 20, 0, 123).on(2024, 7, 31).to_string(),
26
+ "2024-07-31T15:20:00.000000123",
27
+ );
28
+ ```
29
+
30
+ # What is "civil" time?
31
+
32
+ A civil datetime is a calendar date and a clock time. It also goes by the
33
+ names "naive," "local" or "plain." The most important thing to understand
34
+ about civil time is that it does not correspond to a precise instant in
35
+ time. This is in contrast to types like [`Timestamp`](crate::Timestamp) and
36
+ [`Zoned`](crate::Zoned), which _do_ correspond to a precise instant in time (to
37
+ nanosecond precision).
38
+
39
+ Because a civil datetime _never_ has a time zone associated with it, and
40
+ because some time zones have transitions that skip or repeat clock times, it
41
+ follows that not all civil datetimes precisely map to a single instant in time.
42
+ For example, `2024-03-10 02:30` never existed on a clock in `America/New_York`
43
+ because the 2 o'clock hour was skipped when the clocks were "moved forward"
44
+ for daylight saving time. Conversely, `2024-11-03 01:30` occurred twice in
45
+ `America/New_York` because the 1 o'clock hour was repeated when clocks were
46
+ "moved backward" for daylight saving time. (When time is skipped, it's called a
47
+ "gap." When time is repeated, it's called a "fold.")
48
+
49
+ In contrast, an instant in time (that is, `Timestamp` or `Zoned`) can _always_
50
+ be converted to a civil datetime. And, when a civil datetime is combined
51
+ with its time zone identifier _and_ its offset, the resulting machine readable
52
+ string is unambiguous 100% of the time:
53
+
54
+ ```
55
+ use jiff::{civil::date, tz::TimeZone};
56
+
57
+ let tz = TimeZone::get("America/New_York")?;
58
+ let dt = date(2024, 11, 3).at(1, 30, 0, 0);
59
+ // It's ambiguous, so asking for an unambiguous instant presents an error!
60
+ assert!(tz.to_ambiguous_zoned(dt).unambiguous().is_err());
61
+ // Gives you the earlier time in a fold, i.e., before DST ends:
62
+ assert_eq!(
63
+ tz.to_ambiguous_zoned(dt).earlier()?.to_string(),
64
+ "2024-11-03T01:30:00-04:00[America/New_York]",
65
+ );
66
+ // Gives you the later time in a fold, i.e., after DST ends.
67
+ // Notice the offset change from the previous example!
68
+ assert_eq!(
69
+ tz.to_ambiguous_zoned(dt).later()?.to_string(),
70
+ "2024-11-03T01:30:00-05:00[America/New_York]",
71
+ );
72
+ // "Just give me something reasonable"
73
+ assert_eq!(
74
+ tz.to_ambiguous_zoned(dt).compatible()?.to_string(),
75
+ "2024-11-03T01:30:00-04:00[America/New_York]",
76
+ );
77
+
78
+ # Ok::<(), Box<dyn std::error::Error>>(())
79
+ ```
80
+
81
+ # When should I use civil time?
82
+
83
+ Here is a likely non-exhaustive list of reasons why you might want to use
84
+ civil time:
85
+
86
+ * When you want or need to deal with calendar and clock units as an
87
+ intermediate step before and/or after associating it with a time zone. For
88
+ example, perhaps you need to parse strings like `2000-01-01T00:00:00` from a
89
+ CSV file that have no time zone or offset information, but the time zone is
90
+ implied through some out-of-band mechanism.
91
+ * When time zone is actually irrelevant. For example, a fitness tracking app
92
+ that reminds you to work-out at 6am local time, regardless of which time zone
93
+ you're in.
94
+ * When you need to perform arithmetic that deliberately ignores daylight
95
+ saving time.
96
+ * When interacting with legacy systems or systems that specifically do not
97
+ support time zones.
98
+ */
99
+
100
+ pub use self::{
101
+ date::{Date, DateArithmetic, DateDifference, DateSeries, DateWith},
102
+ datetime::{
103
+ DateTime, DateTimeArithmetic, DateTimeDifference, DateTimeRound,
104
+ DateTimeSeries, DateTimeWith,
105
+ },
106
+ iso_week_date::ISOWeekDate,
107
+ time::{
108
+ Time, TimeArithmetic, TimeDifference, TimeRound, TimeSeries, TimeWith,
109
+ },
110
+ weekday::{Weekday, WeekdaysForward, WeekdaysReverse},
111
+ };
112
+
113
+ mod date;
114
+ mod datetime;
115
+ mod iso_week_date;
116
+ mod time;
117
+ mod weekday;
118
+
119
+ /// The era corresponding to a particular year.
120
+ ///
121
+ /// The BCE era corresponds to years less than or equal to `0`, while the CE
122
+ /// era corresponds to years greater than `0`.
123
+ ///
124
+ /// In particular, this crate allows years to be negative and also to be `0`,
125
+ /// which is contrary to the common practice of excluding the year `0` when
126
+ /// writing dates for the Gregorian calendar. Moreover, common practice eschews
127
+ /// negative years in favor of labeling a year with an era notation. That is,
128
+ /// the year `1 BCE` is year `0` in this crate. The year `2 BCE` is the year
129
+ /// `-1` in this crate.
130
+ ///
131
+ /// To get the year in its era format, use [`Date::era_year`].
132
+ #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
133
+ pub enum Era {
134
+ /// The "before common era" era.
135
+ ///
136
+ /// This corresponds to all years less than or equal to `0`.
137
+ ///
138
+ /// This is precisely equivalent to the "BC" or "before Christ" era.
139
+ BCE,
140
+ /// The "common era" era.
141
+ ///
142
+ /// This corresponds to all years greater than `0`.
143
+ ///
144
+ /// This is precisely equivalent to the "AD" or "anno Domini" or "in the
145
+ /// year of the Lord" era.
146
+ CE,
147
+ }
148
+
149
+ /// Creates a new `DateTime` value in a `const` context.
150
+ ///
151
+ /// This is a convenience free function for [`DateTime::constant`]. It is
152
+ /// intended to provide a terse syntax for constructing `DateTime` values from
153
+ /// parameters that are known to be valid.
154
+ ///
155
+ /// # Panics
156
+ ///
157
+ /// This routine panics when [`DateTime::new`] would return an error. That
158
+ /// is, when the given components do not correspond to a valid datetime.
159
+ /// Namely, all of the following must be true:
160
+ ///
161
+ /// * The year must be in the range `-9999..=9999`.
162
+ /// * The month must be in the range `1..=12`.
163
+ /// * The day must be at least `1` and must be at most the number of days
164
+ /// in the corresponding month. So for example, `2024-02-29` is valid but
165
+ /// `2023-02-29` is not.
166
+ /// * `0 <= hour <= 23`
167
+ /// * `0 <= minute <= 59`
168
+ /// * `0 <= second <= 59`
169
+ /// * `0 <= subsec_nanosecond <= 999,999,999`
170
+ ///
171
+ /// Similarly, when used in a const context, invalid parameters will prevent
172
+ /// your Rust program from compiling.
173
+ ///
174
+ /// # Example
175
+ ///
176
+ /// ```
177
+ /// use jiff::civil::DateTime;
178
+ ///
179
+ /// let d = DateTime::constant(2024, 2, 29, 21, 30, 5, 123_456_789);
180
+ /// assert_eq!(d.date().year(), 2024);
181
+ /// assert_eq!(d.date().month(), 2);
182
+ /// assert_eq!(d.date().day(), 29);
183
+ /// assert_eq!(d.time().hour(), 21);
184
+ /// assert_eq!(d.time().minute(), 30);
185
+ /// assert_eq!(d.time().second(), 5);
186
+ /// assert_eq!(d.time().millisecond(), 123);
187
+ /// assert_eq!(d.time().microsecond(), 456);
188
+ /// assert_eq!(d.time().nanosecond(), 789);
189
+ /// ```
190
+ #[inline]
191
+ pub const fn datetime(
192
+ year: i16,
193
+ month: i8,
194
+ day: i8,
195
+ hour: i8,
196
+ minute: i8,
197
+ second: i8,
198
+ subsec_nanosecond: i32,
199
+ ) -> DateTime {
200
+ DateTime::constant(
201
+ year,
202
+ month,
203
+ day,
204
+ hour,
205
+ minute,
206
+ second,
207
+ subsec_nanosecond,
208
+ )
209
+ }
210
+
211
+ /// Creates a new `Date` value in a `const` context.
212
+ ///
213
+ /// This is a convenience free function for [`Date::constant`]. It is intended
214
+ /// to provide a terse syntax for constructing `Date` values from parameters
215
+ /// that are known to be valid.
216
+ ///
217
+ /// # Panics
218
+ ///
219
+ /// This routine panics when [`Date::new`] would return an error. That is,
220
+ /// when the given year-month-day does not correspond to a valid date.
221
+ /// Namely, all of the following must be true:
222
+ ///
223
+ /// * The year must be in the range `-9999..=9999`.
224
+ /// * The month must be in the range `1..=12`.
225
+ /// * The day must be at least `1` and must be at most the number of days
226
+ /// in the corresponding month. So for example, `2024-02-29` is valid but
227
+ /// `2023-02-29` is not.
228
+ ///
229
+ /// Similarly, when used in a const context, invalid parameters will prevent
230
+ /// your Rust program from compiling.
231
+ ///
232
+ /// # Example
233
+ ///
234
+ /// ```
235
+ /// use jiff::civil::date;
236
+ ///
237
+ /// let d = date(2024, 2, 29);
238
+ /// assert_eq!(d.year(), 2024);
239
+ /// assert_eq!(d.month(), 2);
240
+ /// assert_eq!(d.day(), 29);
241
+ /// ```
242
+ #[inline]
243
+ pub const fn date(year: i16, month: i8, day: i8) -> Date {
244
+ Date::constant(year, month, day)
245
+ }
246
+
247
+ /// Creates a new `Time` value in a `const` context.
248
+ ///
249
+ /// This is a convenience free function for [`Time::constant`]. It is intended
250
+ /// to provide a terse syntax for constructing `Time` values from parameters
251
+ /// that are known to be valid.
252
+ ///
253
+ /// # Panics
254
+ ///
255
+ /// This panics if the given values do not correspond to a valid `Time`.
256
+ /// All of the following conditions must be true:
257
+ ///
258
+ /// * `0 <= hour <= 23`
259
+ /// * `0 <= minute <= 59`
260
+ /// * `0 <= second <= 59`
261
+ /// * `0 <= subsec_nanosecond <= 999,999,999`
262
+ ///
263
+ /// Similarly, when used in a const context, invalid parameters will
264
+ /// prevent your Rust program from compiling.
265
+ ///
266
+ /// # Example
267
+ ///
268
+ /// This shows an example of a valid time in a `const` context:
269
+ ///
270
+ /// ```
271
+ /// use jiff::civil::Time;
272
+ ///
273
+ /// const BEDTIME: Time = Time::constant(21, 30, 5, 123_456_789);
274
+ /// assert_eq!(BEDTIME.hour(), 21);
275
+ /// assert_eq!(BEDTIME.minute(), 30);
276
+ /// assert_eq!(BEDTIME.second(), 5);
277
+ /// assert_eq!(BEDTIME.millisecond(), 123);
278
+ /// assert_eq!(BEDTIME.microsecond(), 456);
279
+ /// assert_eq!(BEDTIME.nanosecond(), 789);
280
+ /// assert_eq!(BEDTIME.subsec_nanosecond(), 123_456_789);
281
+ /// ```
282
+ #[inline]
283
+ pub const fn time(
284
+ hour: i8,
285
+ minute: i8,
286
+ second: i8,
287
+ subsec_nanosecond: i32,
288
+ ) -> Time {
289
+ Time::constant(hour, minute, second, subsec_nanosecond)
290
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/time.rs ADDED
The diff for this file is too large to render. See raw diff
 
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/civil/weekday.rs ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::{error::Error, shared::util::itime::IWeekday, util::b};
2
+
3
+ /// A representation for the day of the week.
4
+ ///
5
+ /// The default representation follows ISO 8601. That is, the week starts with
6
+ /// Monday and numbering starts at `1`. However, the various constructors and
7
+ /// accessors support using other schemes in wide use:
8
+ ///
9
+ /// * [`Weekday::from_monday_zero_offset`] builds a weekday from
10
+ /// a scheme that starts the week on Monday at offset `0`, while
11
+ /// [`Weekday::to_monday_zero_offset`] converts to it.
12
+ /// * [`Weekday::from_monday_one_offset`] builds a weekday from a scheme
13
+ /// that starts the week on Monday at offset `1` (the default representation),
14
+ /// while [`Weekday::to_monday_one_offset`] converts to it.
15
+ /// * [`Weekday::from_sunday_zero_offset`] builds a weekday from
16
+ /// a scheme that starts the week on Sunday at offset `0`, while
17
+ /// [`Weekday::to_sunday_zero_offset`] converts to it.
18
+ /// * [`Weekday::from_sunday_one_offset`] builds a weekday from
19
+ /// a scheme that starts the week on Sunday at offset `1`, while
20
+ /// [`Weekday::to_sunday_one_offset`] converts to it.
21
+ ///
22
+ /// # Arithmetic
23
+ ///
24
+ /// This type provides [`Weekday::wrapping_add`] and [`Weekday::wrapping_sub`]
25
+ /// for performing wrapping arithmetic on weekdays. These are also available
26
+ /// via operator overloading:
27
+ ///
28
+ /// ```
29
+ /// use jiff::civil::Weekday;
30
+ ///
31
+ /// assert_eq!(Weekday::Monday + 1, Weekday::Tuesday);
32
+ /// assert_eq!(Weekday::Sunday - 1, Weekday::Saturday);
33
+ /// ```
34
+ ///
35
+ /// # Comparisons
36
+ ///
37
+ /// This type provides `Eq` and `PartialEq` trait implementations for easy
38
+ /// comparison:
39
+ ///
40
+ /// ```
41
+ /// use jiff::civil::Weekday;
42
+ ///
43
+ /// assert_eq!(Weekday::Wednesday, Weekday::Wednesday + 7);
44
+ /// assert_ne!(Weekday::Thursday, Weekday::Friday);
45
+ /// ```
46
+ ///
47
+ /// But this type specifically does not provide `Ord` or `PartialOrd` trait
48
+ /// implementations. Such an implementation would require deciding whether
49
+ /// Sunday is less than Monday or greater than Monday. The former case
50
+ /// corresponds to a week scheme where Sunday is the first day in the week,
51
+ /// where as the latter corresponds to a scheme where Monday is the first day.
52
+ /// Since both schemes are in widespread use, it would be inappropriate to bake
53
+ /// in an assumption of one or the other. Instead, one can convert a weekday
54
+ /// into the desired offset scheme, and then compare the offsets:
55
+ ///
56
+ /// ```
57
+ /// use jiff::civil::Weekday;
58
+ ///
59
+ /// let (sun, mon) = (Weekday::Sunday, Weekday::Monday);
60
+ /// assert!(sun.to_sunday_zero_offset() < mon.to_sunday_zero_offset());
61
+ /// assert!(sun.to_monday_zero_offset() > mon.to_monday_zero_offset());
62
+ /// ```
63
+ ///
64
+ /// # Example
65
+ ///
66
+ /// This example shows the result of converting to and from different schemes:
67
+ ///
68
+ /// ```
69
+ /// use jiff::civil::Weekday;
70
+ ///
71
+ /// // The different representations of Monday.
72
+ /// assert_eq!(Weekday::Monday.to_monday_zero_offset(), 0);
73
+ /// assert_eq!(Weekday::Monday.to_monday_one_offset(), 1);
74
+ /// assert_eq!(Weekday::Monday.to_sunday_zero_offset(), 1);
75
+ /// assert_eq!(Weekday::Monday.to_sunday_one_offset(), 2);
76
+ ///
77
+ /// // The different representations of Sunday.
78
+ /// assert_eq!(Weekday::Sunday.to_monday_zero_offset(), 6);
79
+ /// assert_eq!(Weekday::Sunday.to_monday_one_offset(), 7);
80
+ /// assert_eq!(Weekday::Sunday.to_sunday_zero_offset(), 0);
81
+ /// assert_eq!(Weekday::Sunday.to_sunday_one_offset(), 1);
82
+ /// ```
83
+ #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
84
+ #[repr(u8)]
85
+ #[allow(missing_docs)]
86
+ pub enum Weekday {
87
+ Monday = 1,
88
+ Tuesday = 2,
89
+ Wednesday = 3,
90
+ Thursday = 4,
91
+ Friday = 5,
92
+ Saturday = 6,
93
+ Sunday = 7,
94
+ }
95
+
96
+ impl Weekday {
97
+ /// Convert an offset to a structured `Weekday`.
98
+ ///
99
+ /// The offset should be from a scheme where the first day of the week
100
+ /// is Monday and starts numbering at `0`.
101
+ ///
102
+ /// # Errors
103
+ ///
104
+ /// This returns an error when the given offset is not in the range
105
+ /// `0..=6`.
106
+ ///
107
+ /// # Example
108
+ ///
109
+ /// ```
110
+ /// use jiff::civil::Weekday;
111
+ ///
112
+ /// let weekday = Weekday::from_monday_zero_offset(3)?;
113
+ /// assert_eq!(weekday, Weekday::Thursday);
114
+ ///
115
+ /// assert!(Weekday::from_monday_zero_offset(7).is_err());
116
+ /// assert!(Weekday::from_monday_zero_offset(-1).is_err());
117
+ ///
118
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
119
+ /// ```
120
+ #[inline]
121
+ pub fn from_monday_zero_offset(offset: i8) -> Result<Weekday, Error> {
122
+ Ok(Weekday::from_monday_zero_offset_unchecked(
123
+ b::WeekdayMondayZero::check(offset)?,
124
+ ))
125
+ }
126
+
127
+ #[inline]
128
+ fn from_monday_zero_offset_unchecked(offset: impl Into<i64>) -> Weekday {
129
+ match offset.into() {
130
+ 0 => Weekday::Monday,
131
+ 1 => Weekday::Tuesday,
132
+ 2 => Weekday::Wednesday,
133
+ 3 => Weekday::Thursday,
134
+ 4 => Weekday::Friday,
135
+ 5 => Weekday::Saturday,
136
+ 6 => Weekday::Sunday,
137
+ _ => unreachable!(),
138
+ }
139
+ }
140
+
141
+ /// Convert an offset to a structured `Weekday`.
142
+ ///
143
+ /// The offset should be from a scheme where the first day of the week
144
+ /// is Monday and starts numbering at `1`.
145
+ ///
146
+ /// # Errors
147
+ ///
148
+ /// This returns an error when the given offset is not in the range
149
+ /// `1..=7`.
150
+ ///
151
+ /// # Example
152
+ ///
153
+ /// ```
154
+ /// use jiff::civil::Weekday;
155
+ ///
156
+ /// let weekday = Weekday::from_monday_one_offset(4)?;
157
+ /// assert_eq!(weekday, Weekday::Thursday);
158
+ ///
159
+ /// assert!(Weekday::from_monday_one_offset(8).is_err());
160
+ /// assert!(Weekday::from_monday_one_offset(0).is_err());
161
+ ///
162
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
163
+ /// ```
164
+ #[inline]
165
+ pub fn from_monday_one_offset(offset: i8) -> Result<Weekday, Error> {
166
+ let offset = b::WeekdayMondayOne::check(offset)?;
167
+ Weekday::from_monday_zero_offset(offset - 1)
168
+ }
169
+
170
+ /// Convert an offset to a structured `Weekday`.
171
+ ///
172
+ /// The offset should be from a scheme where the first day of the week
173
+ /// is Sunday and starts numbering at `0`.
174
+ ///
175
+ /// # Errors
176
+ ///
177
+ /// This returns an error when the given offset is not in the range
178
+ /// `0..=6`.
179
+ ///
180
+ /// # Example
181
+ ///
182
+ /// ```
183
+ /// use jiff::civil::Weekday;
184
+ ///
185
+ /// let weekday = Weekday::from_sunday_zero_offset(0)?;
186
+ /// assert_eq!(weekday, Weekday::Sunday);
187
+ /// let weekday = Weekday::from_sunday_zero_offset(4)?;
188
+ /// assert_eq!(weekday, Weekday::Thursday);
189
+ ///
190
+ /// assert!(Weekday::from_sunday_zero_offset(7).is_err());
191
+ /// assert!(Weekday::from_sunday_zero_offset(-1).is_err());
192
+ ///
193
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
194
+ /// ```
195
+ #[inline]
196
+ pub fn from_sunday_zero_offset(offset: i8) -> Result<Weekday, Error> {
197
+ let offset = b::WeekdaySundayZero::check(offset)?;
198
+ Weekday::from_monday_zero_offset((offset - 1).rem_euclid(7))
199
+ }
200
+
201
+ /// Convert an offset to a structured `Weekday`.
202
+ ///
203
+ /// The offset should be from a scheme where the first day of the week
204
+ /// is Sunday and starts numbering at `1`.
205
+ ///
206
+ /// # Errors
207
+ ///
208
+ /// This returns an error when the given offset is not in the range
209
+ /// `1..=7`.
210
+ ///
211
+ /// # Example
212
+ ///
213
+ /// ```
214
+ /// use jiff::civil::Weekday;
215
+ ///
216
+ /// let weekday = Weekday::from_sunday_one_offset(5)?;
217
+ /// assert_eq!(weekday, Weekday::Thursday);
218
+ ///
219
+ /// assert!(Weekday::from_sunday_one_offset(8).is_err());
220
+ /// assert!(Weekday::from_sunday_one_offset(0).is_err());
221
+ ///
222
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
223
+ /// ```
224
+ #[inline]
225
+ pub fn from_sunday_one_offset(offset: i8) -> Result<Weekday, Error> {
226
+ let offset = b::WeekdaySundayOne::check(offset)?;
227
+ Weekday::from_monday_zero_offset((offset - 2).rem_euclid(7))
228
+ }
229
+
230
+ /// Returns this weekday as an offset.
231
+ ///
232
+ /// The offset returned is computed based on a week that starts with Monday
233
+ /// and begins numbering at `0`.
234
+ ///
235
+ /// # Example
236
+ ///
237
+ /// ```
238
+ /// use jiff::civil::Weekday;
239
+ ///
240
+ /// assert_eq!(Weekday::Thursday.to_monday_zero_offset(), 3);
241
+ ///
242
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
243
+ /// ```
244
+ #[inline]
245
+ pub fn to_monday_zero_offset(self) -> i8 {
246
+ self.to_monday_one_offset() - 1
247
+ }
248
+
249
+ /// Returns this weekday as an offset.
250
+ ///
251
+ /// The offset returned is computed based on a week that starts with Monday
252
+ /// and begins numbering at `1`.
253
+ ///
254
+ /// # Example
255
+ ///
256
+ /// ```
257
+ /// use jiff::civil::Weekday;
258
+ ///
259
+ /// assert_eq!(Weekday::Thursday.to_monday_one_offset(), 4);
260
+ ///
261
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
262
+ /// ```
263
+ #[inline]
264
+ pub fn to_monday_one_offset(self) -> i8 {
265
+ self as i8
266
+ }
267
+
268
+ /// Returns this weekday as an offset.
269
+ ///
270
+ /// The offset returned is computed based on a week that starts with Sunday
271
+ /// and begins numbering at `0`.
272
+ ///
273
+ /// # Example
274
+ ///
275
+ /// ```
276
+ /// use jiff::civil::Weekday;
277
+ ///
278
+ /// assert_eq!(Weekday::Thursday.to_sunday_zero_offset(), 4);
279
+ ///
280
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
281
+ /// ```
282
+ #[inline]
283
+ pub fn to_sunday_zero_offset(self) -> i8 {
284
+ let offset = self.to_monday_one_offset();
285
+ if offset == 7 {
286
+ 0
287
+ } else {
288
+ offset
289
+ }
290
+ }
291
+
292
+ /// Returns this weekday as an offset.
293
+ ///
294
+ /// The offset returned is computed based on a week that starts with Sunday
295
+ /// and begins numbering at `1`.
296
+ ///
297
+ /// # Example
298
+ ///
299
+ /// ```
300
+ /// use jiff::civil::Weekday;
301
+ ///
302
+ /// assert_eq!(Weekday::Thursday.to_sunday_one_offset(), 5);
303
+ ///
304
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
305
+ /// ```
306
+ #[inline]
307
+ pub fn to_sunday_one_offset(self) -> i8 {
308
+ self.to_sunday_zero_offset() + 1
309
+ }
310
+
311
+ /// Returns the next weekday, wrapping around at the end of week to the
312
+ /// beginning of the week.
313
+ ///
314
+ /// This is a convenience routing for calling [`Weekday::wrapping_add`]
315
+ /// with a value of `1`.
316
+ ///
317
+ /// # Example
318
+ ///
319
+ /// ```
320
+ /// use jiff::civil::Weekday;
321
+ ///
322
+ /// assert_eq!(Weekday::Wednesday.next(), Weekday::Thursday);
323
+ /// assert_eq!(Weekday::Sunday.next(), Weekday::Monday);
324
+ /// assert_eq!(Weekday::Saturday.next(), Weekday::Sunday);
325
+ /// ```
326
+ #[inline]
327
+ pub fn next(self) -> Weekday {
328
+ self.wrapping_add(1)
329
+ }
330
+
331
+ /// Returns the previous weekday, wrapping around at the beginning of week
332
+ /// to the end of the week.
333
+ ///
334
+ /// This is a convenience routing for calling [`Weekday::wrapping_sub`]
335
+ /// with a value of `1`.
336
+ ///
337
+ /// # Example
338
+ ///
339
+ /// ```
340
+ /// use jiff::civil::Weekday;
341
+ ///
342
+ /// assert_eq!(Weekday::Wednesday.previous(), Weekday::Tuesday);
343
+ /// assert_eq!(Weekday::Sunday.previous(), Weekday::Saturday);
344
+ /// assert_eq!(Weekday::Saturday.previous(), Weekday::Friday);
345
+ /// ```
346
+ #[inline]
347
+ pub fn previous(self) -> Weekday {
348
+ self.wrapping_sub(1)
349
+ }
350
+
351
+ /// Returns the number of days from `other` to this weekday.
352
+ ///
353
+ /// Adding the returned number of days to `other` is guaranteed to sum to
354
+ /// this weekday. The number of days returned is guaranteed to be in the
355
+ /// range `0..=6`.
356
+ ///
357
+ /// # Example
358
+ ///
359
+ /// ```
360
+ /// use jiff::civil::Weekday;
361
+ ///
362
+ /// assert_eq!(Weekday::Friday.since(Weekday::Tuesday), 3);
363
+ /// assert_eq!(Weekday::Tuesday.since(Weekday::Tuesday), 0);
364
+ /// assert_eq!(Weekday::Monday.since(Weekday::Sunday), 1);
365
+ /// assert_eq!(Weekday::Sunday.since(Weekday::Monday), 6);
366
+ /// ```
367
+ #[inline]
368
+ pub fn since(self, other: Weekday) -> i8 {
369
+ (self.to_monday_zero_offset() - other.to_monday_zero_offset())
370
+ .rem_euclid(7)
371
+ }
372
+
373
+ /// Returns the number of days until `other` from this weekday.
374
+ ///
375
+ /// Adding the returned number of days to this weekday is guaranteed to sum
376
+ /// to `other` weekday. The number of days returned is guaranteed to be in
377
+ /// the range `0..=6`.
378
+ ///
379
+ /// # Example
380
+ ///
381
+ /// ```
382
+ /// use jiff::civil::Weekday;
383
+ ///
384
+ /// assert_eq!(Weekday::Friday.until(Weekday::Tuesday), 4);
385
+ /// assert_eq!(Weekday::Tuesday.until(Weekday::Tuesday), 0);
386
+ /// assert_eq!(Weekday::Monday.until(Weekday::Sunday), 6);
387
+ /// assert_eq!(Weekday::Sunday.until(Weekday::Monday), 1);
388
+ /// ```
389
+ #[inline]
390
+ pub fn until(self, other: Weekday) -> i8 {
391
+ other.since(self)
392
+ }
393
+
394
+ /// Add the given number of days to this weekday, using wrapping arithmetic,
395
+ /// and return the resulting weekday.
396
+ ///
397
+ /// Adding a multiple of `7` (including `0`) is guaranteed to produce the
398
+ /// same weekday as this one.
399
+ ///
400
+ /// Note that this routine is also available via the `+` operator.
401
+ ///
402
+ /// # Example
403
+ ///
404
+ /// ```
405
+ /// use jiff::civil::Weekday;
406
+ ///
407
+ /// assert_eq!(Weekday::Sunday.wrapping_add(1), Weekday::Monday);
408
+ /// assert_eq!(Weekday::Sunday.wrapping_add(2), Weekday::Tuesday);
409
+ /// assert_eq!(Weekday::Saturday.wrapping_add(1), Weekday::Sunday);
410
+ /// assert_eq!(Weekday::Saturday.wrapping_add(7), Weekday::Saturday);
411
+ /// assert_eq!(Weekday::Sunday.wrapping_add(-1), Weekday::Saturday);
412
+ /// ```
413
+ ///
414
+ /// Wrapping arithmetic is also performed by the `+` operator:
415
+ ///
416
+ /// ```
417
+ /// use jiff::civil::Weekday;
418
+ ///
419
+ /// assert_eq!(Weekday::Sunday + 1, Weekday::Monday);
420
+ /// assert_eq!(Weekday::Sunday + 2, Weekday::Tuesday);
421
+ /// assert_eq!(Weekday::Saturday + 1, Weekday::Sunday);
422
+ /// assert_eq!(Weekday::Saturday + 7, Weekday::Saturday);
423
+ /// assert_eq!(Weekday::Sunday + -1, Weekday::Saturday);
424
+ /// // The weekday can also be on the right hand side of addition:
425
+ /// assert_eq!(1 + Weekday::Sunday, Weekday::Monday);
426
+ /// ```
427
+ #[inline]
428
+ pub fn wrapping_add<D: Into<i64>>(self, days: D) -> Weekday {
429
+ let start = i64::from(self.to_monday_zero_offset());
430
+ let rhs = days.into();
431
+ let end = start.wrapping_add(rhs).rem_euclid(7);
432
+ // Always valid because of the mod 7 above.
433
+ Weekday::from_monday_zero_offset_unchecked(end)
434
+ }
435
+
436
+ /// Subtract the given number of days from this weekday, using wrapping
437
+ /// arithmetic, and return the resulting weekday.
438
+ ///
439
+ /// Subtracting a multiple of `7` (including `0`) is guaranteed to produce
440
+ /// the same weekday as this one.
441
+ ///
442
+ /// Note that this routine is also available via the `-` operator.
443
+ ///
444
+ /// # Example
445
+ ///
446
+ /// ```
447
+ /// use jiff::civil::Weekday;
448
+ ///
449
+ /// assert_eq!(Weekday::Sunday.wrapping_sub(1), Weekday::Saturday);
450
+ /// assert_eq!(Weekday::Sunday.wrapping_sub(2), Weekday::Friday);
451
+ /// assert_eq!(Weekday::Saturday.wrapping_sub(1), Weekday::Friday);
452
+ /// assert_eq!(Weekday::Saturday.wrapping_sub(7), Weekday::Saturday);
453
+ /// assert_eq!(Weekday::Sunday.wrapping_sub(-1), Weekday::Monday);
454
+ /// ```
455
+ ///
456
+ /// Wrapping arithmetic is also performed by the `-` operator:
457
+ ///
458
+ /// ```
459
+ /// use jiff::civil::Weekday;
460
+ ///
461
+ /// assert_eq!(Weekday::Sunday - 1, Weekday::Saturday);
462
+ /// assert_eq!(Weekday::Sunday - 2, Weekday::Friday);
463
+ /// assert_eq!(Weekday::Saturday - 1, Weekday::Friday);
464
+ /// assert_eq!(Weekday::Saturday - 7, Weekday::Saturday);
465
+ /// assert_eq!(Weekday::Sunday - -1, Weekday::Monday);
466
+ /// ```
467
+ ///
468
+ /// Unlike addition, since subtraction is not commutative and negating a
469
+ /// weekday has no semantic meaning, the weekday cannot be on the right
470
+ /// hand side of the `-` operator.
471
+ #[inline]
472
+ pub fn wrapping_sub<D: Into<i64>>(self, days: D) -> Weekday {
473
+ self.wrapping_add(-days.into())
474
+ }
475
+
476
+ /// Starting with this weekday, this returns an unending iterator that
477
+ /// cycles forward through the days of the week.
478
+ ///
479
+ /// # Example
480
+ ///
481
+ /// ```
482
+ /// use jiff::civil::Weekday;
483
+ ///
484
+ /// let mut it = Weekday::Tuesday.cycle_forward();
485
+ /// assert_eq!(it.next(), Some(Weekday::Tuesday));
486
+ /// assert_eq!(it.next(), Some(Weekday::Wednesday));
487
+ /// assert_eq!(it.next(), Some(Weekday::Thursday));
488
+ /// assert_eq!(it.next(), Some(Weekday::Friday));
489
+ /// assert_eq!(it.next(), Some(Weekday::Saturday));
490
+ /// assert_eq!(it.next(), Some(Weekday::Sunday));
491
+ /// assert_eq!(it.next(), Some(Weekday::Monday));
492
+ /// assert_eq!(it.next(), Some(Weekday::Tuesday));
493
+ /// ```
494
+ #[inline]
495
+ pub fn cycle_forward(self) -> WeekdaysForward {
496
+ let nexts = [
497
+ self,
498
+ self.wrapping_add(1),
499
+ self.wrapping_add(2),
500
+ self.wrapping_add(3),
501
+ self.wrapping_add(4),
502
+ self.wrapping_add(5),
503
+ self.wrapping_add(6),
504
+ ];
505
+ WeekdaysForward { it: nexts.into_iter().cycle() }
506
+ }
507
+
508
+ /// Starting with this weekday, this returns an unending iterator that
509
+ /// cycles backward through the days of the week.
510
+ ///
511
+ /// # Example
512
+ ///
513
+ /// ```
514
+ /// use jiff::civil::Weekday;
515
+ ///
516
+ /// let mut it = Weekday::Tuesday.cycle_reverse();
517
+ /// assert_eq!(it.next(), Some(Weekday::Tuesday));
518
+ /// assert_eq!(it.next(), Some(Weekday::Monday));
519
+ /// assert_eq!(it.next(), Some(Weekday::Sunday));
520
+ /// assert_eq!(it.next(), Some(Weekday::Saturday));
521
+ /// assert_eq!(it.next(), Some(Weekday::Friday));
522
+ /// assert_eq!(it.next(), Some(Weekday::Thursday));
523
+ /// assert_eq!(it.next(), Some(Weekday::Wednesday));
524
+ /// assert_eq!(it.next(), Some(Weekday::Tuesday));
525
+ /// ```
526
+ #[inline]
527
+ pub fn cycle_reverse(self) -> WeekdaysReverse {
528
+ let nexts = [
529
+ self,
530
+ self.wrapping_sub(1),
531
+ self.wrapping_sub(2),
532
+ self.wrapping_sub(3),
533
+ self.wrapping_sub(4),
534
+ self.wrapping_sub(5),
535
+ self.wrapping_sub(6),
536
+ ];
537
+ WeekdaysReverse { it: nexts.into_iter().cycle() }
538
+ }
539
+ }
540
+
541
+ impl Weekday {
542
+ #[inline]
543
+ pub(crate) fn from_iweekday(iweekday: IWeekday) -> Weekday {
544
+ match iweekday.to_monday_one_offset() {
545
+ 1 => Weekday::Monday,
546
+ 2 => Weekday::Tuesday,
547
+ 3 => Weekday::Wednesday,
548
+ 4 => Weekday::Thursday,
549
+ 5 => Weekday::Friday,
550
+ 6 => Weekday::Saturday,
551
+ 7 => Weekday::Sunday,
552
+ _ => unreachable!(),
553
+ }
554
+ }
555
+
556
+ #[inline]
557
+ pub(crate) fn to_iweekday(self) -> IWeekday {
558
+ IWeekday::from_monday_one_offset(self.to_monday_one_offset())
559
+ }
560
+ }
561
+
562
+ impl core::ops::Add<i8> for Weekday {
563
+ type Output = Weekday;
564
+
565
+ #[inline]
566
+ fn add(self, rhs: i8) -> Weekday {
567
+ self.wrapping_add(rhs)
568
+ }
569
+ }
570
+
571
+ impl core::ops::Add<i16> for Weekday {
572
+ type Output = Weekday;
573
+
574
+ #[inline]
575
+ fn add(self, rhs: i16) -> Weekday {
576
+ self.wrapping_add(rhs)
577
+ }
578
+ }
579
+
580
+ impl core::ops::Add<i32> for Weekday {
581
+ type Output = Weekday;
582
+
583
+ #[inline]
584
+ fn add(self, rhs: i32) -> Weekday {
585
+ self.wrapping_add(rhs)
586
+ }
587
+ }
588
+
589
+ impl core::ops::Add<i64> for Weekday {
590
+ type Output = Weekday;
591
+
592
+ #[inline]
593
+ fn add(self, rhs: i64) -> Weekday {
594
+ self.wrapping_add(rhs)
595
+ }
596
+ }
597
+
598
+ // Since addition is commutative, we don't might if users write `n + weekday`
599
+ // or `weekday + n`.
600
+
601
+ impl core::ops::Add<Weekday> for i8 {
602
+ type Output = Weekday;
603
+
604
+ #[inline]
605
+ fn add(self, rhs: Weekday) -> Weekday {
606
+ rhs.wrapping_add(self)
607
+ }
608
+ }
609
+
610
+ impl core::ops::Add<Weekday> for i16 {
611
+ type Output = Weekday;
612
+
613
+ #[inline]
614
+ fn add(self, rhs: Weekday) -> Weekday {
615
+ rhs.wrapping_add(self)
616
+ }
617
+ }
618
+
619
+ impl core::ops::Add<Weekday> for i32 {
620
+ type Output = Weekday;
621
+
622
+ #[inline]
623
+ fn add(self, rhs: Weekday) -> Weekday {
624
+ rhs.wrapping_add(self)
625
+ }
626
+ }
627
+
628
+ impl core::ops::Add<Weekday> for i64 {
629
+ type Output = Weekday;
630
+
631
+ #[inline]
632
+ fn add(self, rhs: Weekday) -> Weekday {
633
+ rhs.wrapping_add(self)
634
+ }
635
+ }
636
+
637
+ impl core::ops::AddAssign<i8> for Weekday {
638
+ #[inline]
639
+ fn add_assign(&mut self, rhs: i8) {
640
+ *self = *self + rhs;
641
+ }
642
+ }
643
+
644
+ impl core::ops::AddAssign<i16> for Weekday {
645
+ #[inline]
646
+ fn add_assign(&mut self, rhs: i16) {
647
+ *self = *self + rhs;
648
+ }
649
+ }
650
+
651
+ impl core::ops::AddAssign<i32> for Weekday {
652
+ #[inline]
653
+ fn add_assign(&mut self, rhs: i32) {
654
+ *self = *self + rhs;
655
+ }
656
+ }
657
+
658
+ impl core::ops::AddAssign<i64> for Weekday {
659
+ #[inline]
660
+ fn add_assign(&mut self, rhs: i64) {
661
+ *self = *self + rhs;
662
+ }
663
+ }
664
+
665
+ // Subtraction isn't commutative, so we only define it when the right hand
666
+ // side is an integer. Otherwise we'd need a concept of what it means to
667
+ // "negate" a weekday, which doesn't really make sense?
668
+
669
+ impl core::ops::Sub<i8> for Weekday {
670
+ type Output = Weekday;
671
+
672
+ #[inline]
673
+ fn sub(self, rhs: i8) -> Weekday {
674
+ self.wrapping_sub(rhs)
675
+ }
676
+ }
677
+
678
+ impl core::ops::Sub<i16> for Weekday {
679
+ type Output = Weekday;
680
+
681
+ #[inline]
682
+ fn sub(self, rhs: i16) -> Weekday {
683
+ self.wrapping_sub(rhs)
684
+ }
685
+ }
686
+
687
+ impl core::ops::Sub<i32> for Weekday {
688
+ type Output = Weekday;
689
+
690
+ #[inline]
691
+ fn sub(self, rhs: i32) -> Weekday {
692
+ self.wrapping_sub(rhs)
693
+ }
694
+ }
695
+
696
+ impl core::ops::Sub<i64> for Weekday {
697
+ type Output = Weekday;
698
+
699
+ #[inline]
700
+ fn sub(self, rhs: i64) -> Weekday {
701
+ self.wrapping_sub(rhs)
702
+ }
703
+ }
704
+
705
+ impl core::ops::SubAssign<i8> for Weekday {
706
+ #[inline]
707
+ fn sub_assign(&mut self, rhs: i8) {
708
+ *self = *self - rhs;
709
+ }
710
+ }
711
+
712
+ impl core::ops::SubAssign<i16> for Weekday {
713
+ #[inline]
714
+ fn sub_assign(&mut self, rhs: i16) {
715
+ *self = *self - rhs;
716
+ }
717
+ }
718
+
719
+ impl core::ops::SubAssign<i32> for Weekday {
720
+ #[inline]
721
+ fn sub_assign(&mut self, rhs: i32) {
722
+ *self = *self - rhs;
723
+ }
724
+ }
725
+
726
+ impl core::ops::SubAssign<i64> for Weekday {
727
+ #[inline]
728
+ fn sub_assign(&mut self, rhs: i64) {
729
+ *self = *self - rhs;
730
+ }
731
+ }
732
+
733
+ #[cfg(test)]
734
+ impl quickcheck::Arbitrary for Weekday {
735
+ fn arbitrary(g: &mut quickcheck::Gen) -> Weekday {
736
+ let offset = b::WeekdayMondayZero::arbitrary(g);
737
+ Weekday::from_monday_zero_offset(offset).unwrap()
738
+ }
739
+
740
+ fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Weekday>> {
741
+ alloc::boxed::Box::new(
742
+ self.to_monday_zero_offset()
743
+ .shrink()
744
+ .filter_map(|n| Weekday::from_monday_zero_offset(n).ok()),
745
+ )
746
+ }
747
+ }
748
+
749
+ /// An unending iterator of the days of the week.
750
+ ///
751
+ /// This iterator is created by calling [`Weekday::cycle_forward`].
752
+ #[derive(Clone, Debug)]
753
+ pub struct WeekdaysForward {
754
+ it: core::iter::Cycle<core::array::IntoIter<Weekday, 7>>,
755
+ }
756
+
757
+ impl Iterator for WeekdaysForward {
758
+ type Item = Weekday;
759
+
760
+ #[inline]
761
+ fn next(&mut self) -> Option<Weekday> {
762
+ self.it.next()
763
+ }
764
+ }
765
+
766
+ impl core::iter::FusedIterator for WeekdaysForward {}
767
+
768
+ /// An unending iterator of the days of the week in reverse.
769
+ ///
770
+ /// This iterator is created by calling [`Weekday::cycle_reverse`].
771
+ #[derive(Clone, Debug)]
772
+ pub struct WeekdaysReverse {
773
+ it: core::iter::Cycle<core::array::IntoIter<Weekday, 7>>,
774
+ }
775
+
776
+ impl Iterator for WeekdaysReverse {
777
+ type Item = Weekday;
778
+
779
+ #[inline]
780
+ fn next(&mut self) -> Option<Weekday> {
781
+ self.it.next()
782
+ }
783
+ }
784
+
785
+ impl core::iter::FusedIterator for WeekdaysReverse {}
786
+
787
+ #[cfg(test)]
788
+ mod tests {
789
+ use super::*;
790
+
791
+ quickcheck::quickcheck! {
792
+ fn prop_since_add_equals_self(wd1: Weekday, wd2: Weekday) -> bool {
793
+ let days = wd1.since(wd2);
794
+ wd2.wrapping_add(days) == wd1
795
+ }
796
+
797
+ fn prop_until_add_equals_other(wd1: Weekday, wd2: Weekday) -> bool {
798
+ let days = wd1.until(wd2);
799
+ wd1.wrapping_add(days) == wd2
800
+ }
801
+ }
802
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/duration.rs ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use core::time::Duration as UnsignedDuration;
2
+
3
+ use crate::{
4
+ error::{duration::Error as E, ErrorContext},
5
+ Error, SignedDuration, Span,
6
+ };
7
+
8
+ /// An internal type for abstracting over different duration types.
9
+ #[derive(Clone, Copy, Debug)]
10
+ pub(crate) enum Duration {
11
+ Span(Span),
12
+ Signed(SignedDuration),
13
+ Unsigned(UnsignedDuration),
14
+ }
15
+
16
+ impl Duration {
17
+ /// Convert this to a signed duration.
18
+ ///
19
+ /// This returns an error only in the case where this is an unsigned
20
+ /// duration with a number of whole seconds that exceeds `|i64::MIN|`.
21
+ #[cfg_attr(feature = "perf-inline", inline(always))]
22
+ pub(crate) fn to_signed(&self) -> Result<SDuration<'_>, Error> {
23
+ match *self {
24
+ Duration::Span(ref span) => Ok(SDuration::Span(span)),
25
+ Duration::Signed(sdur) => Ok(SDuration::Absolute(sdur)),
26
+ Duration::Unsigned(udur) => {
27
+ let sdur = SignedDuration::try_from(udur)
28
+ .context(E::RangeUnsignedDuration)?;
29
+ Ok(SDuration::Absolute(sdur))
30
+ }
31
+ }
32
+ }
33
+
34
+ /// Negates this duration.
35
+ ///
36
+ /// When the duration is a span, this can never fail because a span defines
37
+ /// its min and max values such that negation is always possible.
38
+ ///
39
+ /// When the duration is signed, then this attempts to return a signed
40
+ /// duration and only falling back to an unsigned duration when the number
41
+ /// of seconds corresponds to `i64::MIN`.
42
+ ///
43
+ /// When the duration is unsigned, then this fails when the whole seconds
44
+ /// exceed the absolute value of `i64::MIN`. Otherwise, a signed duration
45
+ /// is returned.
46
+ ///
47
+ /// The failures for large unsigned durations here are okay because the
48
+ /// point at which absolute durations overflow on negation, they would also
49
+ /// cause overflow when adding or subtracting to *any* valid datetime value
50
+ /// for *any* datetime type in this crate. So while the error message may
51
+ /// be different, the actual end result is the same (failure).
52
+ ///
53
+ /// TODO: Write unit tests for this.
54
+ #[cfg_attr(feature = "perf-inline", inline(always))]
55
+ pub(crate) fn checked_neg(self) -> Result<Duration, Error> {
56
+ match self {
57
+ Duration::Span(span) => Ok(Duration::Span(span.negate())),
58
+ Duration::Signed(sdur) => {
59
+ // We try to stick with signed durations, but in the case
60
+ // where negation fails, we can represent its negation using
61
+ // an unsigned duration.
62
+ if let Some(sdur) = sdur.checked_neg() {
63
+ Ok(Duration::Signed(sdur))
64
+ } else {
65
+ let udur = UnsignedDuration::new(
66
+ i64::MIN.unsigned_abs(),
67
+ sdur.subsec_nanos().unsigned_abs(),
68
+ );
69
+ Ok(Duration::Unsigned(udur))
70
+ }
71
+ }
72
+ Duration::Unsigned(udur) => {
73
+ // We can permit negating i64::MIN.unsigned_abs() to
74
+ // i64::MIN, but we need to handle it specially since
75
+ // i64::MIN.unsigned_abs() exceeds i64::MAX.
76
+ let sdur = if udur.as_secs() == i64::MIN.unsigned_abs() {
77
+ SignedDuration::new_without_nano_overflow(
78
+ i64::MIN,
79
+ // OK because `udur.subsec_nanos()` < 999_999_999.
80
+ -i32::try_from(udur.subsec_nanos()).unwrap(),
81
+ )
82
+ } else {
83
+ // The negation here is always correct because it can only
84
+ // panic with `sdur.as_secs() == i64::MIN`, which is
85
+ // impossible because it must be positive.
86
+ //
87
+ // Otherwise, this is the only failure point in this entire
88
+ // routine. And specifically, we fail here in precisely
89
+ // the cases where `udur.as_secs() > |i64::MIN|`.
90
+ -SignedDuration::try_from(udur)
91
+ .context(E::FailedNegateUnsignedDuration)?
92
+ };
93
+ Ok(Duration::Signed(sdur))
94
+ }
95
+ }
96
+ }
97
+
98
+ /// Returns true if and only if this duration is negative.
99
+ #[cfg_attr(feature = "perf-inline", inline(always))]
100
+ pub(crate) fn is_negative(&self) -> bool {
101
+ match *self {
102
+ Duration::Span(ref span) => span.is_negative(),
103
+ Duration::Signed(ref sdur) => sdur.is_negative(),
104
+ Duration::Unsigned(_) => false,
105
+ }
106
+ }
107
+ }
108
+
109
+ impl From<Span> for Duration {
110
+ #[inline]
111
+ fn from(span: Span) -> Duration {
112
+ Duration::Span(span)
113
+ }
114
+ }
115
+
116
+ impl From<SignedDuration> for Duration {
117
+ #[inline]
118
+ fn from(sdur: SignedDuration) -> Duration {
119
+ Duration::Signed(sdur)
120
+ }
121
+ }
122
+
123
+ impl From<UnsignedDuration> for Duration {
124
+ #[inline]
125
+ fn from(udur: UnsignedDuration) -> Duration {
126
+ Duration::Unsigned(udur)
127
+ }
128
+ }
129
+
130
+ /// An internal type for abstracting over signed durations.
131
+ ///
132
+ /// This is typically converted to from a `Duration`. It enables callers
133
+ /// downstream to implement datetime arithmetic on only two duration types
134
+ /// instead of doing it for three duration types (including
135
+ /// `std::time::Duration`).
136
+ ///
137
+ /// The main thing making this idea work is that if an unsigned duration cannot
138
+ /// fit into a signed duration, then it would overflow any calculation on any
139
+ /// datetime type in Jiff anyway. If this weren't true, then we'd need to
140
+ /// support doing actual arithmetic with unsigned durations separately from
141
+ /// signed durations.
142
+ #[derive(Clone, Copy, Debug)]
143
+ pub(crate) enum SDuration<'a> {
144
+ Span(&'a Span),
145
+ Absolute(SignedDuration),
146
+ }
.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.20/src/error/civil.rs ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::error;
2
+
3
+ #[derive(Clone, Debug)]
4
+ pub(crate) enum Error {
5
+ FailedAddDays,
6
+ FailedAddDurationOverflowing,
7
+ FailedAddSpanDate,
8
+ FailedAddSpanOverflowing,
9
+ FailedAddSpanTime,
10
+ IllegalTimeWithMicrosecond,
11
+ IllegalTimeWithMillisecond,
12
+ IllegalTimeWithNanosecond,
13
+ OverflowDaysDuration,
14
+ OverflowTimeNanoseconds,
15
+ }
16
+
17
+ impl From<Error> for error::Error {
18
+ #[cold]
19
+ #[inline(never)]
20
+ fn from(err: Error) -> error::Error {
21
+ error::ErrorKind::Civil(err).into()
22
+ }
23
+ }
24
+
25
+ impl error::IntoError for Error {
26
+ fn into_error(self) -> error::Error {
27
+ self.into()
28
+ }
29
+ }
30
+
31
+ impl core::fmt::Display for Error {
32
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
33
+ use self::Error::*;
34
+
35
+ match *self {
36
+ FailedAddDays => f.write_str("failed to add days to date"),
37
+ FailedAddDurationOverflowing => {
38
+ f.write_str("failed to add overflowing duration")
39
+ }
40
+ FailedAddSpanDate => f.write_str("failed to add span to date"),
41
+ FailedAddSpanOverflowing => {
42
+ f.write_str("failed to add overflowing span")
43
+ }
44
+ FailedAddSpanTime => f.write_str("failed to add span to time"),
45
+ IllegalTimeWithMicrosecond => f.write_str(
46
+ "cannot set both `TimeWith::microsecond` \
47
+ and `TimeWith::subsec_nanosecond`",
48
+ ),
49
+ IllegalTimeWithMillisecond => f.write_str(
50
+ "cannot set both `TimeWith::millisecond` \
51
+ and `TimeWith::subsec_nanosecond`",
52
+ ),
53
+ IllegalTimeWithNanosecond => f.write_str(
54
+ "cannot set both `TimeWith::nanosecond` \
55
+ and `TimeWith::subsec_nanosecond`",
56
+ ),
57
+ OverflowDaysDuration => f.write_str(
58
+ "number of days derived from duration exceed's \
59
+ Jiff's datetime limits",
60
+ ),
61
+ OverflowTimeNanoseconds => {
62
+ f.write_str("adding duration to time overflowed")
63
+ }
64
+ }
65
+ }
66
+ }