-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmain.rs
More file actions
288 lines (226 loc) · 7.54 KB
/
Copy pathmain.rs
File metadata and controls
288 lines (226 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
trait Calculator {
// Performs a primary calculation
fn calculate(&self, a: i32, b: i32) -> i32;
// Modifies internal state based on input
fn accumulate(&mut self, value: i32);
// Returns the current internal state
fn get_value(&self) -> i32;
// Returns an identifier for the calculator type
fn id(&self) -> u8;
}
trait CarrierValue {
fn carrier_value(self) -> i32;
}
impl CarrierValue for i32 {
fn carrier_value(self) -> i32 {
self + 1
}
}
impl CarrierValue for [i32; 3] {
fn carrier_value(self) -> i32 {
self[0] + self[1] + self[2]
}
}
impl CarrierValue for &str {
fn carrier_value(self) -> i32 {
self.len() as i32
}
}
trait PrimitiveTraitObject {
fn doubled(&self) -> i32;
}
impl PrimitiveTraitObject for i32 {
fn doubled(&self) -> i32 {
*self * 2
}
}
fn use_primitive_trait_object(value: &dyn PrimitiveTraitObject) -> i32 {
value.doubled()
}
// --- First Implementation ---
struct SimpleAdder {
current_total: i32,
}
impl Calculator for SimpleAdder {
fn calculate(&self, a: i32, b: i32) -> i32 {
a + b // Simple addition
}
fn accumulate(&mut self, value: i32) {
self.current_total += value;
}
fn get_value(&self) -> i32 {
self.current_total
}
fn id(&self) -> u8 {
1 // Identifier for SimpleAdder
}
}
// --- Second Implementation ---
struct Multiplier {
current_product: i32,
}
impl Calculator for Multiplier {
fn calculate(&self, a: i32, b: i32) -> i32 {
a * b // Multiplication
}
fn accumulate(&mut self, value: i32) {
if value == 0 {
// Explicitly do nothing if value is 0, preserving the current product.
return;
}
if self.current_product == 0 {
// If the current product is 0, accumulating a non-zero value should
// just set the product to that value. Avoids 0 * value = 0.
self.current_product = value;
} else {
// Otherwise (current product is non-zero and value is non-zero), multiply.
self.current_product *= value;
}
}
fn get_value(&self) -> i32 {
self.current_product
}
fn id(&self) -> u8 {
6 // Identifier for Multiplier
}
}
// Takes an immutable trait object reference
fn perform_calculation(calc: &dyn Calculator, x: i32, y: i32) -> i32 {
calc.calculate(x, y)
}
// Takes a mutable trait object reference
fn update_state(calc: &mut dyn Calculator, val: i32) {
calc.accumulate(val);
}
// Checks properties via immutable trait object
fn check_properties(calc: &dyn Calculator) -> (i32, u8) {
(calc.get_value(), calc.id())
}
trait Score {
fn score(&self, base: i32) -> i32;
fn tag(&self) -> i32;
}
impl Score for () {
fn score(&self, base: i32) -> i32 {
base + 1
}
fn tag(&self) -> i32 {
7
}
}
// Zero-sized struct receiver: same class of bug as `()`.
#[derive(Clone, Copy)]
struct Marker;
impl Score for Marker {
fn score(&self, base: i32) -> i32 {
base * 2
}
fn tag(&self) -> i32 {
11
}
}
// Forwarding impl mirroring core's `impl Debug for &T`, which is where the
// original failure surfaced: `<&() as Debug>::fmt` re-dispatching to
// `<() as Debug>::fmt` on the pointee.
impl<T: Score> Score for &T {
fn score(&self, base: i32) -> i32 {
(**self).score(base)
}
fn tag(&self) -> i32 {
(**self).tag()
}
}
// Generic dispatch so the receiver type is only known at monomorphization.
fn total<T: Score>(value: T, base: i32) -> i32 {
value.score(base) + value.tag()
}
fn by_ref<T: Score>(value: &T, base: i32) -> i32 {
value.score(base)
}
fn main() {
assert!(41i32.carrier_value() == 42);
assert!([2, 3, 5].carrier_value() == 10);
assert!("carrier".carrier_value() == 7);
let primitive = 21i32;
let primitive_object: &dyn PrimitiveTraitObject = &primitive;
assert!(primitive_object.doubled() == 42);
assert!(use_primitive_trait_object(&primitive) == 42);
let mut adder = SimpleAdder { current_total: 10 };
// Direct calls
assert!(adder.calculate(5, 3) == 8);
assert!(adder.get_value() == 10);
assert!(adder.id() == 1);
adder.accumulate(5);
assert!(adder.get_value() == 15);
// Immutable Trait Object (&dyn Calculator)
let adder_ref: &dyn Calculator = &adder;
assert!(adder_ref.calculate(10, 20) == 30);
assert!(adder_ref.get_value() == 15); // State reflects previous mutation
assert!(adder_ref.id() == 1);
// Pass immutable trait object to function
let result1 = perform_calculation(&adder, 100, 50);
assert!(result1 == 150);
let (val1, id1) = check_properties(&adder);
assert!(val1 == 15);
assert!(id1 == 1);
// Mutable Trait Object (&mut dyn Calculator)
let adder_mut_ref: &mut dyn Calculator = &mut adder;
adder_mut_ref.accumulate(-7);
// Check state change via original variable AFTER mutable borrow ends
assert!(adder.get_value() == 8); // 15 - 7 = 8
// Pass mutable trait object to function
update_state(&mut adder, 2);
assert!(adder.get_value() == 10); // 8 + 2 = 10
let mut multiplier = Multiplier { current_product: 2 };
// Direct calls
assert!(multiplier.calculate(5, 3) == 15);
assert!(multiplier.get_value() == 2);
assert!(multiplier.id() == 6);
multiplier.accumulate(4); // state becomes 2 * 4 = 8
assert!(multiplier.get_value() == 8);
// Immutable Trait Object (&dyn Calculator)
let multiplier_ref: &dyn Calculator = &multiplier;
assert!(multiplier_ref.calculate(6, 7) == 42);
assert!(multiplier_ref.get_value() == 8); // State reflects previous mutation
assert!(multiplier_ref.id() == 6);
// Pass immutable trait object to function
let result2 = perform_calculation(&multiplier, -2, 9);
assert!(result2 == -18);
let (val2, id2) = check_properties(&multiplier);
assert!(val2 == 8);
assert!(id2 == 6);
// Mutable Trait Object (&mut dyn Calculator)
let multiplier_mut_ref: &mut dyn Calculator = &mut multiplier;
multiplier_mut_ref.accumulate(3);
// Check state change via original variable AFTER mutable borrow ends
assert!(multiplier.get_value() == 24); // 8 * 3 = 24
// Pass mutable trait object to function
update_state(&mut multiplier, -2);
assert!(multiplier.get_value() == -48); // 24 * -2 = -48
// Check zero accumulation behaviour
update_state(&mut multiplier, 0);
assert!(multiplier.get_value() == -48); // Should not change when multiplying by 0
// Final check: use different trait objects in sequence
let calc1: &dyn Calculator = &SimpleAdder { current_total: 100 };
let calc2: &dyn Calculator = &Multiplier { current_product: 10 };
assert!(perform_calculation(calc1, 1, 1) == 2);
assert!(check_properties(calc1) == (100, 1));
assert!(perform_calculation(calc2, 2, 3) == 6);
assert!(check_properties(calc2) == (10, 6));
// Credit from this point on: AnuthaDev
// Direct calls on the unit value.
let unit = ();
assert!(unit.score(10) == 11);
assert!(unit.tag() == 7);
// Through generics (T = () and T = Marker).
assert!(total((), 100) == 108);
assert!(total(Marker, 100) == 211);
// Through the &T forwarding impl (T = () — the original failure shape).
assert!(by_ref(&(), 5) == 6);
assert!(total(&(), 20) == 28);
assert!(by_ref(&Marker, 5) == 10);
// Double indirection for good measure.
let unit_ref = &();
assert!(by_ref(&unit_ref, 3) == 4);
// If we reach here without panic, the test passes
}