endgame_direction 0.4.0

A library for representing cardinal and ordinal directions.
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use endgame_direction::{Direction, DirectionSet};
use itertools::Itertools;
use std::borrow::Borrow;

#[test]
fn directionset_borrow() {
    for dirs_vec1 in Direction::VALUES.iter().powerset() {
        for dirs_vec2 in Direction::VALUES.iter().powerset() {
            let dirs1 = DirectionSet::from_iter(dirs_vec1.iter().cloned());
            let dirs2 = DirectionSet::from_iter(dirs_vec2.iter().cloned());
            assert!(
                dirs1 != dirs2 || dirs1.borrow() == dirs2.borrow(),
                "Borrow condition not satisfied: {:?} == {:?} but {:?} != {:?}",
                dirs1,
                dirs2,
                dirs1.borrow(),
                dirs2.borrow()
            );
        }
    }
}

#[test]
fn direction_containment() {
    let all_directions = Direction::VALUES;
    // Verify that the cardinal and ordinal directions are subsets of the
    // complete set of directions.
    for (name, dirs) in vec![
        ("Cardinal", Direction::CARDINAL),
        ("Ordinal", Direction::ORDINAL),
    ] {
        assert!(
            !dirs.is_superset(all_directions),
            "The {name} directions ({dirs}) should not be a superset of all directions ({all_directions})."
        );
        assert!(
            all_directions.is_superset(dirs),
            "All directions ({all_directions}) are not a superset the {name} directions ({dirs})"
        );
        assert!(
            dirs.is_subset(all_directions),
            "The {name} directions ({dirs}) are not a subset of all directions ({all_directions})."
        );
        assert!(
            !all_directions.is_subset(dirs),
            "The {name} directions ({dirs}) should not be a subset of all directions ({all_directions})."
        )
    }

    // Verify that the cardinal and ordinal directions are disjoint.
    assert!(
        Direction::CARDINAL
            .intersection(Direction::ORDINAL)
            .is_empty(),
        "Cardinal and Ordinal directions are not disjoint."
    );

    // Check the set differencing over cardinal and ordinal directions behaves
    // as expected.
    assert_eq!(
        Direction::VALUES.difference(Direction::CARDINAL),
        *Direction::ORDINAL,
        "Removing the cardinal directions from all directions should yield the ordinal directions."
    );
    assert_eq!(
        Direction::VALUES.difference(Direction::ORDINAL),
        *Direction::CARDINAL,
        "Removing the ordinal directions from all directions should yield the cardinal directions."
    );

    assert_eq!(
        *Direction::VALUES,
        Direction::CARDINAL.union(Direction::ORDINAL),
        "Union of the cardinal and ordinal directions should be the same as all directions.")
}

#[test]
fn test_is_ordinal() {
    for dir in Direction::ORDINAL {
        assert!(
            dir.is_ordinal(),
            "Ordinal direction {dir} is not in the ordinal set."
        );
        assert!(
            !dir.is_cardinal(),
            "Non-ordinal direction {dir} is incorrectly in the ordinal set."
        );
    }
}

#[test]
fn test_is_cardinal() {
    for dir in Direction::CARDINAL {
        assert!(
            dir.is_cardinal(),
            "Cardinal direction {dir} is not in the cardinal set."
        );
        assert!(
            !dir.is_ordinal(),
            "Non-cardinal direction {dir} is incorrectly in the cardinal set."
        );
    }
}

#[test]
fn test_containment() {
    for (name, dirs) in vec![
        ("Cardinal", Direction::CARDINAL),
        ("Ordinal", Direction::ORDINAL),
    ] {
        for dir in dirs {
            assert!(
                dirs.contains(dir),
                "Direction {dir} in set {name} ({dirs}) via iterator, but not by containment."
            );
        }
    }
}

#[test]
fn test_direction_rotation() {
    for dir in Direction::VALUES {
        assert_eq!(
            dir,
            dir.clockwise().counter_clockwise(),
            "clockwise and counter-clockwise on {} are not inverses.",
            dir
        );

        assert_eq!(
            dir.rotate(1),
            dir.clockwise(),
            "Rotating by a single step should be equivalent to rotating clockwise.",
        );

        assert_eq!(
            dir.rotate(-1),
            dir.counter_clockwise(),
            "Rotating by negative step should be equivalent to rotating counter-clockwise.",
        );

        assert_eq!(
            dir.rotate(8),
            dir,
            "Rotating by eight steps should be an identity.",
        );

        assert_eq!(
            dir.rotate(-8),
            dir,
            "Rotating by negative eight steps should be an identity.",
        );
    }
}

#[test]
fn test_direction_invertibility() {
    for dir in Direction::VALUES {
        assert_eq!(
            dir, !!dir,
            "opposite operation on {} is not invertible.",
            dir
        );
    }
}

#[test]
fn test_from_slice() {
    let slice = [
        Direction::North,
        Direction::East,
        Direction::South,
        Direction::West,
    ];
    let dir_set = DirectionSet::from_slice(&slice);
    assert!(
        !dir_set.is_empty(),
        "The set {dir_set} should not be empty."
    );
    assert!(dir_set.contains(Direction::North));
    assert!(dir_set.contains(Direction::East));
    assert!(dir_set.contains(Direction::South));
    assert!(dir_set.contains(Direction::West));
    assert!(!dir_set.contains(Direction::NorthEast));

    let dir_set = dir_set.difference(Direction::CARDINAL);
    assert!(
        dir_set.is_empty(),
        "The set {dir_set} should be empty after removing all cardinal directions."
    );

    let slice = [Direction::West, Direction::West];
    let dir_set = DirectionSet::from_slice(&slice);
    assert!(dir_set.contains(Direction::West));
    assert_eq!(
        dir_set.len(),
        1,
        "The set {dir_set} should just contain West."
    );

    for dir in Direction::VALUES {
        let dir_set = DirectionSet::from_slice(&[dir]);
        assert!(
            dir_set.contains(dir),
            "Direction {dir} should be in the set."
        );
    }

    assert!(
        DirectionSet::from_slice(&[]).is_empty(),
        "DirectionSet from empty slice should be empty."
    );
}

#[test]
fn test_insert_and_remove() {
    let mut dir_set = DirectionSet::new();
    assert!(dir_set.is_empty(), "New direction set should be empty.");

    for dir in Direction::VALUES {
        assert!(
            !dir_set.contains(dir),
            "Direction {dir} should not be in the set: {dir_set}."
        );
        assert!(
            dir_set.insert(dir),
            "Direction {dir} should not be in the set: {dir_set}."
        );
        assert!(
            dir_set.contains(dir),
            "Direction {dir} should now be in the set: {dir_set}."
        );
    }

    for dir in Direction::VALUES {
        assert!(
            dir_set.contains(dir),
            "Direction {dir} should be in the set before removal: {dir_set}."
        );
        assert!(
            dir_set.remove(dir),
            "Direction {dir} should be in the set before removal: {dir_set}."
        );
        assert!(
            !dir_set.contains(dir),
            "Direction {dir} should no longer be in the set: {dir_set}."
        );
    }

    assert!(
        dir_set.is_empty(),
        "Direction set should be empty after removing all directions."
    );
}

#[test]
fn test_iteration() {
    for (name, dirs) in vec![
        ("all", Direction::VALUES),
        ("cardinal", Direction::CARDINAL),
        ("ordinal", Direction::ORDINAL),
    ] {
        let mut dir_set = DirectionSet::new();

        let mut iter = dirs.iter();
        let mut count = 0;
        for dir in dirs {
            assert_eq!(iter.next(), Some(dir));
            count += 1;
            assert!(
                dir_set.insert(dir),
                "Direction {dir} should not have already been in the set: {dir_set}."
            );
            assert!(
                count <= dirs.len(),
                "Iterated over too many directions in {} directions.",
                name
            );
        }
        assert_eq!(
            *dirs, dir_set,
            "Iterator did not iterate over all {} directions.",
            name
        );
        assert_eq!(
            iter.next(),
            None,
            "Iterator did not end after all {} directions.",
            name
        );
    }
}

#[test]
fn test_direction_set_formatting() {
    let dir_set = Direction::VALUES;
    let formatted = format!("{dir_set}");
    assert_eq!(
        formatted, "{East, NorthEast, North, NorthWest, West, SouthWest, South, SouthEast}",
        "Formatted direction set does not match expected output."
    );
    let dir_set = DirectionSet::new();
    let formatted = format!("{dir_set}");
    assert_eq!(
        formatted, "{}",
        "Formatted direction set does not match expected output."
    );
}

#[test]
fn test_direction_angles() {
    use std::f32::consts::PI;

    let mut angle = 0.0;
    for dir in Direction::VALUES {
        // TODO What is really an acceptable error here?
        assert!(
            (dir.angle() - angle).abs() < (8.0 * f32::EPSILON),
            "Direction {dir} has unexpected angle: difference between \
            {} vs {angle} is greater than {}",
            dir.angle(),
            8.0 * f32::EPSILON
        );
        angle += PI / 4.0;
    }
}


#[test]
fn test_direction_short_name_mappings() {
    use Direction::*;
    let cases = [
        (East, "E"),
        (NorthEast, "NE"),
        (North, "N"),
        (NorthWest, "NW"),
        (West, "W"),
        (SouthWest, "SW"),
        (South, "S"),
        (SouthEast, "SE"),
    ];
    for (dir, expected) in cases {
        assert_eq!(dir.short_name(), expected, "short_name mismatch for {dir}");
    }
}

#[test]
fn test_direction_parse_success() {
    use Direction::*;

    let success_cases: &[(&str, Direction)] = &[
        // Single-letter cardinal abbreviations
        ("e", East),
        ("n", North),
        ("w", West),
        ("s", South),
        // Two-letter ordinal abbreviations (mixed case)
        ("ne", NorthEast),
        ("NW", NorthWest),
        ("Se", SouthEast),
        ("sW", SouthWest),
        // Full names
        ("east", East),
        ("north", North),
        ("west", West),
        ("south", South),
        // Ordinals with separators 
        ("north-east", NorthEast),
        ("north_east", NorthEast),
        ("south-west", SouthWest),
        ("south_west", SouthWest),
        ("south west", SouthWest),
        ("north east", NorthEast),
    ];

    for (input, expected) in success_cases {
        let parsed = Direction::parse(input);
        assert_eq!(parsed, Some(*expected), "parse failed for input '{input}'.");
    }
}

#[test]
fn test_direction_parse_failure() {
    // Choose inputs that should not match any direction according to current regexes
    let failure_cases = [
        // Empty and ASCII whitespace-only.
        "",
        " ",
        "\t\t",
        // Non-ASCII/Unicode whitespace-only (should trim to empty or not match)
        "\u{00A0}", // NO-BREAK SPACE
        "\u{2002}", // EN SPACE
        "\u{2003}", // EM SPACE
        "\u{2009}", // THIN SPACE
        "\u{200B}", // ZERO WIDTH SPACE 
        "\u{3000}", // IDEOGRAPHIC SPACE
        // Clearly invalid strings.
        "123",
        "foo",
        // Invalid separator usage with spaces around hyphen (ASCII and Unicode)
        "east- west",         // ASCII space after hyphen is not allowed by the regex
        "north-\u{00A0}east", // NBSP after hyphen should not match
        "north\u{00A0}-east", // NBSP before hyphen should not match
        // Zero width joiners/spaces inserted between words should not match
        "north\u{200B}east",
        "south\u{200B}west",
        // Leading/trailing zero width space around otherwise valid tokens
        "north-east\u{200B}",
        "\u{200B}north-east",
        // Double underscore
        "north__east",
        "-ne",
        "se-",
        "_sw",
    ];

    for input in failure_cases {
        let parsed = Direction::parse(input);
        assert!(parsed.is_none(), "Unexpected parse success for input '{input}': {:?}.", parsed);
    }
}