huub 100.0.0

CP+SAT solver framework built to be reliable, performant, and extensible
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
//! Integer decision variable definitions for the solver layer.

use std::{
	collections::hash_map::{self, VacantEntry},
	iter::{Map, Peekable},
	num::NonZero,
	ops::{Index, IndexMut, Neg, RangeBounds, RangeInclusive},
};

use pindakaas::{Lit as RawLit, Var as RawVar, VarRange, solver::propagation::ExternalPropagation};
use rangelist::{IntervalIterator, RangeList};
use rustc_hash::FxHashMap;

use crate::{
	IntSet, IntVal,
	actions::{
		BoolInspectionActions, IntDecisionActions, IntExplanationActions, IntInspectionActions,
		Trailed, TrailingActions,
	},
	solver::{
		IntLitMeaning, Solver,
		decision::{Decision, DecisionReference, private},
		engine::State,
		solving_context::SolvingContext,
		trail::Trail,
		view::{View, boolean::BoolView},
	},
	views::LinearView,
};

/// An entry in the [`DirectStorage`] that can be used to access the
/// representation of an equality condition, or insert a new literal to
/// represent the condition otherwise.
enum DirectEntry<'a> {
	/// The condition is already stored in the [`DirectStorage`].
	Occupied(View<bool>),
	/// The condition is not yet stored in the [`DirectStorage`].
	Vacant(VacantEntry<'a, IntVal, RawVar>),
}

/// The structure that stores the equality conditions. Equality conditions can
/// either be eagerly crated, and stored as a range of variables, or lazily
/// created and stored in a [`HashMap`] once created.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum DirectStorage {
	/// Variables for all equality conditions are eagerly created and stored in
	/// order
	Eager(VarRange),
	/// Variables for equality conditions are lazily created and stored in a
	/// hashmap
	Lazy(FxHashMap<IntVal, RawVar>),
}

/// Type used resolve (possible) values in the domain to order literals and
/// their tightest literal meaning.
///
/// Used as the return type of [`OrderStorage::resolve_val`].
#[derive(Clone, Debug)]
struct DomainLocation<'a, const OFFSET: usize> {
	/// Tightest value for the less-than literal
	less_val: IntVal,
	/// Tightest value for the greater-than or equal-to literal
	greater_eq_val: IntVal,
	/// Offset of the literal in the variable range.
	offset: [usize; OFFSET],
	/// Iterator in the domain that point to the range in which the value is
	/// located.
	range_iter: RangeIter<'a>,
}

/// The structure used to store information about an integer variable within
/// the solver.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct IntDecision {
	/// The direct encoding of the integer variable.
	///
	/// Literals in this encoding are used to reason about whether an integer
	/// variable takes a certain value.
	pub(crate) direct_encoding: DirectStorage,
	/// The domain of the integer variable at the time of its creation.
	pub(crate) domain: RangeList<IntVal>,
	/// The order encoding of the integer variable.
	///
	/// Literals in this encoding are used to reason about the bounds of the
	/// integer variable.
	pub(crate) order_encoding: OrderStorage,
	/// A Trailed integer representing the current upper bound of the integer
	/// variable.
	///
	/// Note that the lower bound is tracked within [`Self::order_encoding`].
	pub(crate) upper_bound: Trailed<IntVal>,
}

/// The definition given to a lazily created literal.
#[derive(Debug)]
pub(crate) struct LazyLitDef {
	/// The meaning that the literal is meant to represent.
	pub(crate) meaning: IntLitMeaning,
	/// The variable that represent:
	/// - if `meaning` is `LitMeaning::Less(j)`, then `prev` contains the
	///   literal `< i` where `i` is the value right before `j` in the storage.
	/// - if `meaning` is `LitMeaning::Eq(k)`, then `prev` contains the literal
	///   `<j`.
	pub(crate) prev: Option<RawVar>,
	/// The variable that represent the literal `< k` where `k` is the value
	/// right after the value represented by the literal.
	pub(crate) next: Option<RawVar>,
}

/// A storage structure to manage lazily created order literals for an integer
/// variable.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct LazyOrderStorage {
	/// The index of the node with the minimum value in the storage.
	min_index: u32,
	/// The index of the node with the maximum value in the storage.
	max_index: u32,
	/// The index of the node that currently represents the lower bound of the
	/// integer variable.
	lb_index: Trailed<isize>,
	/// The index of the node that currently represents the upper bound of the
	/// integer variable.
	ub_index: Trailed<isize>,
	/// The storage of all currently created nodes containing the order literals
	/// for the integer variable.
	storage: Vec<OrderNode>,
}

/// An entry in [`OrderStorage`] that can be used to access the representation
/// of an inequality condition, or insert a new literal to represent the
/// condition otherwise.
#[derive(Debug)]
enum OrderEntry<'a> {
	/// Entry already exists and was eagerly created.
	Eager(&'a VarRange, usize),
	/// Entry already exists and was lazily created.
	Occupied {
		/// Reference to the storage where the entry is stored.
		storage: &'a mut LazyOrderStorage,
		/// The index of the node in the storage that the entry points to.
		index: u32,
		/// An iterator pointing at the range in the domain in which the value
		/// of which the value of the entry is part.
		range_iter: RangeIter<'a>,
	},
	/// Entry does not exist and can be lazily created.
	Vacant {
		/// Reference to the storage where the new entry will be created.
		storage: &'a mut LazyOrderStorage,
		/// The index of the node that contains the value right before the new
		/// entry that will be created.
		prev_index: IntVal,
		/// An iterator pointing at the range in the domain in which the value
		/// of which the value of the new entry is part.
		range_iter: RangeIter<'a>,
		/// The value for which the entry will be created.
		val: IntVal,
	},
}

/// Type used to store individual entries in [`LazyOrderStorage`].
///
/// ## Warning
///
/// Because the values for literals of `≥` literals are part of the domains, the
/// values included in the node are that for the meaning of the `≥` literal.
/// However, the positive [`RawVar`] is used to represent a `<` literal (because
/// of standard phasing in SAT solvers), which might have a stronger meaning
/// than `< val` because of gaps in the original domain.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct OrderNode {
	/// The value for which `!var` represents `x ≥ val`.
	val: IntVal,
	/// The variable representing `!(x ≥ val)`.
	var: RawVar,
	/// Whether there is a node with a value less than `val`.
	has_prev: bool,
	/// The index of the node with a value less than `val`.
	prev: u32,
	/// Whether there is a node with a value greater than `val`.
	has_next: bool,
	/// The index of the node with a value greater than `val`.
	next: u32,
}

#[derive(Clone, Debug, Eq, PartialEq)]
/// The storage used to store the variables for the inequality conditions.
pub(crate) enum OrderStorage {
	/// Variables for all inequality conditions are eagerly created and stored
	/// in order.
	Eager {
		/// A trailed integer that represents the currently lower bound of the
		/// variable.
		lower_bound: Trailed<IntVal>,
		/// The range of Boolean variables that represent the inequality
		/// conditions.
		storage: VarRange,
	},
	/// Variables for inequality conditions are lazily created and specialized
	/// node structure, a [`LazyOrderStorage`].
	Lazy(LazyOrderStorage),
}

/// Type alias for an iterator that yields the ranges of a [`RangeList`], which
/// is used to represent the domains of an integer variable.
type RangeIter<'a> = Peekable<
	Map<
		<&'a RangeList<IntVal> as IntoIterator>::IntoIter,
		fn(RangeInclusive<&'a IntVal>) -> RangeInclusive<IntVal>,
	>,
>;

/// A direction to search in.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum SearchDirection {
	/// Search from low to high.
	Increasing,
	/// Search from high to low.
	Decreasing,
}

impl Decision<IntVal> {
	/// Return an integer identifier that can be used for this decision.
	pub(crate) fn ident(&self) -> u32 {
		self.0
	}

	/// Return the index used to access this decision in solver storage.
	pub(crate) fn idx(&self) -> usize {
		self.0 as usize
	}
}

impl<Sat: ExternalPropagation> IntDecisionActions<Solver<Sat>> for Decision<IntVal> {
	fn lit(&self, ctx: &mut Solver<Sat>, meaning: IntLitMeaning) -> View<bool> {
		let (mut actions, mut engine) = ctx.as_parts_mut();
		let mut ctx = SolvingContext::new(&mut actions, &mut engine.state);
		self.lit(&mut ctx, meaning)
	}

	fn val_lit(&self, ctx: &mut Solver<Sat>) -> Option<View<bool>> {
		let (mut actions, mut engine) = ctx.as_parts_mut();
		let mut ctx = SolvingContext::new(&mut actions, &mut engine.state);
		IntDecisionActions::val_lit(self, &mut ctx)
	}
}

impl IntExplanationActions<State> for Decision<IntVal> {
	fn lit_relaxed(&self, ctx: &State, mut meaning: IntLitMeaning) -> (View<bool>, IntLitMeaning) {
		debug_assert!(
			!matches!(meaning, IntLitMeaning::Eq(_)),
			"relaxed integer literals are not yet supported for IntLitMeaning::Eq(_)"
		);

		let var_def = &ctx.int_vars[self.idx()];
		// If we are looking for a not-equal literal, try and find it. Return it if we
		// find it, otherwise defer to an order literal.
		if let IntLitMeaning::NotEq(v) = meaning {
			if let Some((bv, _)) = var_def.try_lit(meaning) {
				return (bv, IntLitMeaning::NotEq(v));
			}

			let lb = var_def.lower_bound(&ctx.trail);
			if v < lb {
				meaning = IntLitMeaning::GreaterEq(v + 1);
			} else {
				debug_assert!(v > var_def.upper_bound(&ctx.trail));
				meaning = IntLitMeaning::Less(v);
			}
		}
		// Find the strongest order literal that fits the given meaning.
		match meaning {
			IntLitMeaning::GreaterEq(v) => {
				let (bv, v) = var_def.greater_eq_lit_or_weaker(&ctx.trail, v);
				(bv, IntLitMeaning::GreaterEq(v))
			}
			IntLitMeaning::Less(v) => {
				let (bv, v) = var_def.less_lit_or_weaker(&ctx.trail, v);
				(bv, IntLitMeaning::Less(v))
			}
			_ => unreachable!(),
		}
	}
}

impl<Sat> IntInspectionActions<Solver<Sat>> for Decision<IntVal> {
	fn bounds(&self, ctx: &Solver<Sat>) -> (IntVal, IntVal) {
		let lb = self.min(ctx);
		let ub = self.max(ctx);
		(lb, ub)
	}

	fn domain(&self, ctx: &Solver<Sat>) -> IntSet {
		self.domain(&ctx.engine.borrow().state)
	}

	fn in_domain(&self, ctx: &Solver<Sat>, val: IntVal) -> bool {
		self.in_domain(&ctx.engine.borrow().state, val)
	}

	fn lit_meaning(&self, ctx: &Solver<Sat>, lit: View<bool>) -> Option<IntLitMeaning> {
		self.lit_meaning(&ctx.engine.borrow().state, lit)
	}

	fn max(&self, ctx: &Solver<Sat>) -> IntVal {
		self.max(&ctx.engine.borrow().state)
	}

	fn max_lit(&self, ctx: &Solver<Sat>) -> View<bool> {
		self.max_lit(&ctx.engine.borrow().state)
	}

	fn min(&self, ctx: &Solver<Sat>) -> IntVal {
		self.min(&ctx.engine.borrow().state)
	}

	fn min_lit(&self, ctx: &Solver<Sat>) -> View<bool> {
		self.min_lit(&ctx.engine.borrow().state)
	}

	fn try_lit(&self, ctx: &Solver<Sat>, meaning: IntLitMeaning) -> Option<View<bool>> {
		self.try_lit(&ctx.engine.borrow().state, meaning)
	}

	fn val(&self, ctx: &Solver<Sat>) -> Option<IntVal> {
		let (lb, ub) = self.bounds(ctx);
		if lb == ub { Some(lb) } else { None }
	}
}

impl IntInspectionActions<State> for Decision<IntVal> {
	fn bounds(&self, ctx: &State) -> (IntVal, IntVal) {
		let lb = self.min(ctx);
		let ub = self.max(ctx);
		(lb, ub)
	}

	fn domain(&self, ctx: &State) -> IntSet {
		ctx.int_vars[self.idx()].domain(&ctx.trail)
	}

	fn in_domain(&self, ctx: &State, val: IntVal) -> bool {
		let (lb, ub) = self.bounds(ctx);
		if lb <= val && val <= ub {
			let eq_lit = self.try_lit(ctx, IntLitMeaning::Eq(val));
			if let Some(eq_lit) = eq_lit {
				eq_lit.val(ctx).unwrap_or(true)
			} else {
				true
			}
		} else {
			false
		}
	}

	fn lit_meaning(&self, ctx: &State, lit: View<bool>) -> Option<IntLitMeaning> {
		let BoolView::Lit(lit) = lit.0 else {
			return None;
		};
		let (iv, meaning) = ctx.get_int_lit_meaning(lit)?;
		if *self != iv {
			return None;
		}
		Some(meaning)
	}

	fn max(&self, ctx: &State) -> IntVal {
		ctx.int_vars[self.idx()].upper_bound(&ctx.trail)
	}

	fn max_lit(&self, ctx: &State) -> View<bool> {
		ctx.int_vars[self.idx()].upper_bound_lit(&ctx.trail)
	}

	fn min(&self, ctx: &State) -> IntVal {
		ctx.int_vars[self.idx()].lower_bound(&ctx.trail)
	}

	fn min_lit(&self, ctx: &State) -> View<bool> {
		ctx.int_vars[self.idx()].lower_bound_lit(&ctx.trail)
	}

	fn try_lit(&self, ctx: &State, meaning: IntLitMeaning) -> Option<View<bool>> {
		ctx.int_vars[self.idx()].try_lit(meaning).map(|t| t.0)
	}

	fn val(&self, ctx: &State) -> Option<IntVal> {
		let (lb, ub) = self.bounds(ctx);
		if lb == ub { Some(lb) } else { None }
	}
}

impl Neg for Decision<IntVal> {
	type Output = LinearView<NonZero<IntVal>, IntVal, Self>;

	fn neg(self) -> Self::Output {
		let lin: LinearView<NonZero<IntVal>, IntVal, Self> = self.into();
		-lin
	}
}

impl DirectEntry<'_> {
	/// Extract the [`BoolViewInner`] if the entry is occupied, or insert a new
	/// variable using the given function.
	fn or_insert_with(self, f: impl FnOnce() -> RawVar) -> View<bool> {
		match self {
			DirectEntry::Occupied(bv) => bv,
			DirectEntry::Vacant(no_entry) => {
				let v = f();
				no_entry.insert(v);
				Decision(v.into()).into()
			}
		}
	}
}

impl DirectStorage {
	/// Locate the position in the [`DirectStorage`] that would be used to store
	/// the representation of the condition `= i`. The method will return a
	/// [`DirectEntry`] object that can be used to access the condition as a
	/// [`BoolViewInner`] if it already exists, or insert a new literal to
	/// represent the condition otherwise.
	///
	/// The given `domain` is (in the case of eager creation) used to determine
	/// the offset of the variable in the `VarRange`.
	fn entry(&mut self, domain: &RangeList<IntVal>, i: IntVal) -> DirectEntry<'_> {
		match self {
			DirectStorage::Eager(vars) => {
				// Calculate the offset in the VarRange
				let mut offset = Some(-1); // -1 to account for the lower bound
				for r in domain.iter() {
					if i < *r.start() {
						offset = None;
						break;
					} else if r.contains(&i) {
						offset = Some(offset.unwrap() + i - r.start());
						break;
					} else {
						offset = Some(offset.unwrap() + r.end() - r.start() + 1);
					}
				}
				if let Some(offset) = offset {
					debug_assert!(
						(offset as usize) < vars.len(),
						"var range offset, {}, must be in [{}, {})",
						offset,
						0,
						vars.len(),
					);
					DirectEntry::Occupied(Decision(vars.index(offset as usize).into()).into())
				} else {
					DirectEntry::Occupied(false.into())
				}
			}
			DirectStorage::Lazy(map) => match map.entry(i) {
				hash_map::Entry::Occupied(entry) => {
					DirectEntry::Occupied(Decision((*entry.get()).into()).into())
				}
				hash_map::Entry::Vacant(no_entry) => {
					if domain.contains(&i) {
						DirectEntry::Vacant(no_entry)
					} else {
						DirectEntry::Occupied(false.into())
					}
				}
			},
		}
	}

	/// Return the [`BoolViewInner`] that represent the condition `= i`, if it
	/// already exists.
	///
	/// The given `domain` is (in the case of eager creation) used to determine
	/// the offset of the variable in the `VarRange`.
	fn find(&self, domain: &RangeList<IntVal>, i: IntVal) -> Option<View<bool>> {
		match self {
			DirectStorage::Eager(vars) => {
				// Calculate the offset in the VarRange
				let mut offset = Some(-1); // -1 to account for the lower bound
				for r in domain.iter() {
					if i < *r.start() {
						offset = None;
						break;
					} else if r.contains(&i) {
						offset = Some(offset.unwrap() + i - r.start());
						break;
					} else {
						offset = Some(offset.unwrap() + r.end() - r.start() + 1);
					}
				}
				Some(if let Some(offset) = offset {
					debug_assert!(
						(offset as usize) < vars.len(),
						"var range offset, {}, must be in [{}, {})",
						offset,
						0,
						vars.len(),
					);
					Decision(vars.index(offset as usize).into()).into()
				} else {
					false.into()
				})
			}
			DirectStorage::Lazy(map) => {
				map.get(&i)
					.map(|v| Decision((*v).into()).into())
					.or_else(|| {
						if !domain.contains(&i) {
							Some(false.into())
						} else {
							None
						}
					})
			}
		}
	}
}

impl IntDecision {
	/// Returns the lower and upper bounds of the current state of the integer
	/// variable.
	pub(crate) fn bounds(&self, trail: &impl TrailingActions) -> (IntVal, IntVal) {
		let lb = match &self.order_encoding {
			OrderStorage::Eager { lower_bound, .. } => trail.trailed(*lower_bound),
			OrderStorage::Lazy(storage) => {
				let low = trail.trailed(storage.lb_index);
				if low >= 0 {
					storage.storage[low as usize].val
				} else {
					*self.domain.lower_bound().unwrap()
				}
			}
		};
		(lb, trail.trailed(self.upper_bound))
	}

	/// Returns the current domain of the integer variable.
	pub(crate) fn domain<T>(&self, trail: &T) -> RangeList<IntVal>
	where
		T: TrailingActions,
		Decision<bool>: BoolInspectionActions<T>,
	{
		let (lb, ub) = self.bounds(trail);
		let domain = &self.domain;
		let orig_lb = *domain.lower_bound().unwrap();
		let lb_var = || self.order_encoding.find(domain, orig_lb + 1).map(|v| v.0);
		let orig_ub = *domain.upper_bound().unwrap();
		let ub_var = || self.order_encoding.find(domain, orig_ub).map(|v| v.0);

		match &self.direct_encoding {
			DirectStorage::Eager(direct_range) => {
				let pos = domain.position(&lb).unwrap();
				RangeList::from_sorted_elements(
					domain
						.iter()
						.skip_while(|range| *range.end() < lb)
						.flatten()
						.skip_while(|&v| v < lb)
						.enumerate()
						.map(|(i, v)| {
							(
								v,
								if v == orig_lb {
									lb_var().unwrap()
								} else if v == orig_ub {
									ub_var().unwrap()
								} else {
									direct_range.index(pos + i - 1)
								},
							)
						})
						.take_while(|(v, _)| *v <= ub)
						.filter(|&(_, lit)| Decision::<bool>(lit.into()).val(trail) != Some(false))
						.map(|(v, _)| v),
				)
			}
			DirectStorage::Lazy(hash_map) => RangeList::from_sorted_elements(
				domain
					.iter()
					.skip_while(|range| *range.end() < lb)
					.flatten()
					.skip_while(|&v| v < lb)
					.map(|v| {
						(
							v,
							if v == orig_lb {
								lb_var()
							} else if v == orig_ub {
								ub_var()
							} else {
								hash_map.get(&v).copied()
							},
						)
					})
					.take_while(|(v, _)| *v <= ub)
					.filter(|&(_, lit)| {
						lit.map(|lit| Decision::<bool>(lit.into()).val(trail) != Some(false))
							.unwrap_or(true)
					})
					.map(|(v, _)| v),
			),
		}
	}

	/// Returns the boolean view associated with `≥ v` if it exists or weaker
	/// version otherwise.
	///
	/// ## Warning
	/// This function assumes that `v <= lb`.
	pub(crate) fn greater_eq_lit_or_weaker<T>(&self, trail: &T, v: IntVal) -> (View<bool>, IntVal)
	where
		T: TrailingActions,
		Decision<bool>: BoolInspectionActions<T>,
	{
		debug_assert!(v <= self.lower_bound(trail));
		if v <= *self.domain.lower_bound().unwrap() {
			return (true.into(), v);
		}

		match &self.order_encoding {
			OrderStorage::Eager { storage, .. } => {
				let DomainLocation { offset, .. } = OrderStorage::resolve_val::<1>(&self.domain, v);
				(Decision(!storage.index(offset[0])).into(), v)
			}
			OrderStorage::Lazy(storage) => {
				let mut ret = (true.into(), v);
				let lb_index = trail.trailed(storage.lb_index);
				let mut index = if lb_index < 0 {
					return ret;
				} else {
					lb_index as usize
				};
				while storage.storage[index].val >= v {
					let node = &storage.storage[index];
					let lit: View<bool> = Decision(!node.var).into();
					if let Some(v) = lit.val(trail) {
						debug_assert!(v);
						ret = (lit, node.val);
					}
					if !node.has_prev {
						break;
					}
					index = node.prev as usize;
				}
				ret
			}
		}
	}

	/// Returns the boolean view associated with `< v` if it exists or weaker
	/// version otherwise.
	///
	/// ## Warning
	/// This function assumes that `v >= ub`.
	pub(crate) fn less_lit_or_weaker<T>(&self, trail: &T, v: IntVal) -> (View<bool>, IntVal)
	where
		T: TrailingActions,
		Decision<bool>: BoolInspectionActions<T>,
	{
		if v < self.upper_bound(trail) {
			println!("{}", self.upper_bound(trail));
			println!("What?!");
		}
		debug_assert!(v >= self.upper_bound(trail));
		if v > *self.domain.upper_bound().unwrap() {
			return (true.into(), v);
		}

		match &self.order_encoding {
			OrderStorage::Eager { storage, .. } => {
				let DomainLocation { offset, .. } = OrderStorage::resolve_val::<1>(&self.domain, v);
				let bv = Decision(storage.index(offset[0]).into()).into();
				(bv, v)
			}
			OrderStorage::Lazy(storage) => {
				let mut ret = (true.into(), v);
				let ub_index = trail.trailed(storage.ub_index);
				let mut index = if ub_index < 0 {
					return ret;
				} else {
					ub_index as usize
				};
				while storage.storage[index].val <= v {
					let node = &storage.storage[index];
					let lit: View<bool> = Decision(node.var.into()).into();
					if let Some(v) = lit.val(trail) {
						debug_assert!(v);
						ret = (lit, node.val);
					}
					if !node.has_next {
						break;
					}
					index = node.next as usize;
				}
				ret
			}
		}
	}

	/// Access the Boolean literal with the given meaning, creating it if it is
	/// not yet available.
	pub(crate) fn lit(
		&mut self,
		lit_req: IntLitMeaning,
		mut new_var: impl FnMut(LazyLitDef) -> RawVar,
	) -> (View<bool>, IntLitMeaning) {
		let lb = *self.domain.lower_bound().unwrap();
		let ub = *self.domain.upper_bound().unwrap();

		// Use the order literals when requesting an equality literal of the global
		// bounds.
		let mut lit_req = match lit_req {
			IntLitMeaning::Eq(i) if i == lb => IntLitMeaning::Less(lb + 1),
			IntLitMeaning::NotEq(i) if i == lb => IntLitMeaning::GreaterEq(lb + 1),
			IntLitMeaning::Eq(i) if i == ub => IntLitMeaning::GreaterEq(ub),
			IntLitMeaning::NotEq(i) if i == ub => IntLitMeaning::Less(ub),
			_ => lit_req,
		};

		let bv = match lit_req {
			IntLitMeaning::Eq(i) | IntLitMeaning::NotEq(i) if i < lb || i > ub => {
				matches!(lit_req, IntLitMeaning::NotEq(_)).into()
			}
			IntLitMeaning::Eq(i) | IntLitMeaning::NotEq(i) => {
				let bv = self
					.direct_encoding
					.entry(&self.domain, i)
					.or_insert_with(|| {
						let (entry, prev) =
							self.order_encoding.entry(&self.domain, i).0.or_insert_with(
								|val, prev, next| {
									new_var(LazyLitDef {
										meaning: IntLitMeaning::Less(val),
										prev,
										next,
									})
								},
							);
						let next = entry
							.next_value()
							.or_insert_with(|val, prev, next| {
								new_var(LazyLitDef {
									meaning: IntLitMeaning::Less(val),
									prev,
									next,
								})
							})
							.1;
						new_var(LazyLitDef {
							meaning: IntLitMeaning::Eq(i),
							prev: Some(prev),
							next: Some(next),
						})
					});
				if matches!(lit_req, IntLitMeaning::NotEq(_)) {
					!bv
				} else {
					bv
				}
			}
			IntLitMeaning::GreaterEq(i) | IntLitMeaning::Less(i) if i <= lb => {
				matches!(lit_req, IntLitMeaning::GreaterEq(_)).into()
			}
			IntLitMeaning::GreaterEq(i) | IntLitMeaning::Less(i) if i > ub => {
				matches!(lit_req, IntLitMeaning::Less(_)).into()
			}
			IntLitMeaning::GreaterEq(i) | IntLitMeaning::Less(i) => {
				let (entry, lt, geq) = self.order_encoding.entry(&self.domain, i);
				let var: RawLit = entry
					.or_insert_with(|val, prev, next| {
						new_var(LazyLitDef {
							meaning: IntLitMeaning::Less(val),
							prev,
							next,
						})
					})
					.1
					.into();
				Decision(if matches!(lit_req, IntLitMeaning::GreaterEq(_)) {
					lit_req = IntLitMeaning::GreaterEq(geq);
					!var
				} else {
					lit_req = IntLitMeaning::Less(lt);
					var
				})
				.into()
			}
		};

		(bv, lit_req)
	}

	/// Returns the meaning of a literal in the context of this integer
	/// variable.
	///
	/// # Warning
	///
	/// This method can only be used with literals that were eagerly created for
	/// this integer variable. Lazy literals should be mapped using
	/// [`BoolToIntMap`].
	pub(crate) fn lit_meaning(&self, lit: Decision<bool>) -> IntLitMeaning {
		let var = lit.0.var();
		let ret = |l: IntLitMeaning| {
			if lit.is_negated() { !l } else { l }
		};

		let OrderStorage::Eager { storage, .. } = &self.order_encoding else {
			unreachable!("lit_meaning called on non-eager variable")
		};
		if storage.contains(&var) {
			let mut offset = storage.find(var).unwrap() as IntVal + 1; // +1 because first value is not encoded
			for r in self.domain.iter() {
				let r_len = r.end() - r.start() + 1;
				if offset < r_len {
					return ret(IntLitMeaning::Less(*r.start() + offset));
				} else if offset == r_len && !lit.is_negated() {
					return IntLitMeaning::Less(*r.start() + offset);
				}
				offset -= r_len;
			}
			unreachable!()
		}
		let DirectStorage::Eager(vars) = &self.direct_encoding else {
			unreachable!("lit_meaning called on non-eager variable")
		};
		debug_assert!(vars.contains(&var));
		let mut offset = vars.find(var).unwrap() as IntVal + 1;
		for r in self.domain.iter() {
			let r_len = r.end() - r.start() + 1;
			if offset < r_len {
				return ret(IntLitMeaning::Eq(*r.start() + offset));
			}
			offset -= r_len;
		}
		unreachable!()
	}

	/// Returns the lower bound of the current state of the integer variable.
	pub(crate) fn lower_bound<T>(&self, trail: &T) -> IntVal
	where
		T: TrailingActions,
		Decision<bool>: BoolInspectionActions<T>,
	{
		match &self.order_encoding {
			OrderStorage::Eager { lower_bound, .. } => trail.trailed(*lower_bound),
			OrderStorage::Lazy(storage) => {
				let low = trail.trailed(storage.lb_index);
				if low >= 0 {
					storage.storage[low as usize].val
				} else {
					*self.domain.lower_bound().unwrap()
				}
			}
		}
	}

	/// Returns the boolean view associated with the lower bound of the variable
	/// being this value.
	pub(crate) fn lower_bound_lit(&self, trail: &impl TrailingActions) -> View<bool> {
		match &self.order_encoding {
			OrderStorage::Eager {
				lower_bound,
				storage,
				..
			} => {
				let lb = trail.trailed(*lower_bound);
				if lb == *self.domain.lower_bound().unwrap() {
					true.into()
				} else {
					let DomainLocation { offset, .. } =
						OrderStorage::resolve_val::<1>(&self.domain, lb);
					Decision(!storage.index(offset[0])).into()
				}
			}
			OrderStorage::Lazy(storage) => {
				let lb_index = trail.trailed(storage.lb_index);
				if lb_index >= 0 {
					Decision(!storage[lb_index as u32].var).into()
				} else {
					true.into()
				}
			}
		}
	}

	/// Notify that a new lower bound has been propagated for the variable.
	///
	/// # Warning
	///
	/// This method assumes the literal for the new lower bound has been created
	/// (and propagated).
	pub(crate) fn notify_lower_bound<T>(&mut self, trail: &mut T, val: IntVal)
	where
		T: TrailingActions,
		Decision<bool>: BoolInspectionActions<T>,
	{
		debug_assert!(self.domain.contains(&val));
		debug_assert!(val > self.lower_bound(trail));
		match &self.order_encoding {
			OrderStorage::Eager { lower_bound, .. } => {
				trail.set_trailed(*lower_bound, val);
			}
			OrderStorage::Lazy(
				storage @ LazyOrderStorage {
					min_index,
					lb_index,
					..
				},
			) => {
				let cur_index = trail.trailed(*lb_index);
				let cur_index = if cur_index < 0 {
					*min_index
				} else {
					cur_index as u32
				};
				debug_assert!(storage[cur_index].val <= val);
				let new_index = storage.find_index(cur_index, SearchDirection::Increasing, val);
				debug_assert_eq!(storage[new_index].val, val);
				let old_index = trail.set_trailed(*lb_index, new_index as isize);
				debug_assert!(old_index < 0 || cur_index == old_index as u32);
			}
		}
	}

	/// Notify that a new upper bound has been propagated for the variable.
	///
	/// # Warning
	///
	/// This method assumes the literal for the new upper bound has been created
	/// (and propagated).
	pub(crate) fn notify_upper_bound(&mut self, trail: &mut impl TrailingActions, val: IntVal) {
		debug_assert!(self.domain.contains(&val));
		debug_assert!(val < self.upper_bound(trail));
		trail.set_trailed(self.upper_bound, val);
		if let OrderStorage::Lazy(
			storage @ LazyOrderStorage {
				max_index,
				ub_index,
				..
			},
		) = &self.order_encoding
		{
			let DomainLocation {
				greater_eq_val: val,
				..
			} = OrderStorage::resolve_val::<0>(&self.domain, val + 1);
			let cur_index = trail.trailed(*ub_index);
			let cur_index = if cur_index < 0 {
				*max_index
			} else {
				cur_index as u32
			};
			let new_index = storage.find_index(cur_index, SearchDirection::Decreasing, val);
			debug_assert_eq!(storage[new_index].val, val);
			let old_index = trail.set_trailed(*ub_index, new_index as isize);
			debug_assert!(old_index < 0 || cur_index == old_index as u32);
		}
	}

	/// Method used to strengthen the meaning of a [`LitMeaning::Less`] literal
	/// when possible through gaps in the domain.
	pub(crate) fn tighten_less_lit(&self, val: IntVal) -> IntVal {
		let ranges = self.domain.iter();
		if ranges.len() == 1 {
			debug_assert!(self.domain.contains(&(val - 1)));
			return val;
		}
		let range = ranges.rev().find(|r| *r.start() < val).unwrap();
		if val > *range.end() {
			*range.end() + 1
		} else {
			val
		}
	}

	/// Try and find an (already) existing Boolean literal with the given
	/// meaning
	pub(crate) fn try_lit(&self, lit_req: IntLitMeaning) -> Option<(View<bool>, IntLitMeaning)> {
		let lb = *self.domain.lower_bound().unwrap();
		let ub = *self.domain.upper_bound().unwrap();

		// Use the order literals when requesting an equality literal of the global
		// bounds.
		let mut lit_req = match lit_req {
			IntLitMeaning::Eq(i) if i == lb => IntLitMeaning::Less(lb + 1),
			IntLitMeaning::NotEq(i) if i == lb => IntLitMeaning::GreaterEq(lb + 1),
			IntLitMeaning::Eq(i) if i == ub => IntLitMeaning::GreaterEq(ub),
			IntLitMeaning::NotEq(i) if i == ub => IntLitMeaning::Less(ub),
			_ => lit_req,
		};

		let bv = match lit_req {
			IntLitMeaning::Eq(i) if i < lb || i > ub => false.into(),
			IntLitMeaning::Eq(i) => self.direct_encoding.find(&self.domain, i)?,
			IntLitMeaning::GreaterEq(i) if i <= lb => true.into(),
			IntLitMeaning::GreaterEq(i) if i > ub => false.into(),
			IntLitMeaning::GreaterEq(i) => {
				let (var, _, geq) = self.order_encoding.find(&self.domain, i)?;
				lit_req = IntLitMeaning::GreaterEq(geq);
				Decision(!var).into()
			}
			IntLitMeaning::Less(i) if i <= lb => false.into(),
			IntLitMeaning::Less(i) if i > ub => true.into(),
			IntLitMeaning::Less(i) => {
				let (var, lt, _) = self.order_encoding.find(&self.domain, i)?;
				lit_req = IntLitMeaning::Less(lt);
				Decision(var.into()).into()
			}
			IntLitMeaning::NotEq(i) if i < lb || i > ub => true.into(),
			IntLitMeaning::NotEq(i) => !self.direct_encoding.find(&self.domain, i)?,
		};
		Some((bv, lit_req))
	}

	/// Returns the upper bound of the current state of the integer variable.
	pub(crate) fn upper_bound(&self, trail: &impl TrailingActions) -> IntVal {
		trail.trailed(self.upper_bound)
	}

	/// Returns the boolean view associated with the upper bound of the variable
	/// being this value.
	pub(crate) fn upper_bound_lit(&self, trail: &impl TrailingActions) -> View<bool> {
		match &self.order_encoding {
			OrderStorage::Eager { storage, .. } => {
				let ub = trail.trailed(self.upper_bound);
				if ub == *self.domain.upper_bound().unwrap() {
					true.into()
				} else {
					let DomainLocation { offset, .. } =
						OrderStorage::resolve_val::<1>(&self.domain, ub + 1);
					Decision(storage.index(offset[0]).into()).into()
				}
			}
			OrderStorage::Lazy(storage) => {
				let ub_index = trail.trailed(storage.ub_index);
				if ub_index >= 0 {
					Decision(storage[ub_index as u32].var.into()).into()
				} else {
					true.into()
				}
			}
		}
	}
}

impl DecisionReference for IntVal {
	type Ref = u32;
}
impl private::Sealed for IntVal {}

impl LazyOrderStorage {
	/// Create an empty lazy storage for order literals.
	pub(crate) fn new_in(trail: &mut Trail) -> Self {
		Self {
			min_index: 0,
			max_index: 0,
			lb_index: trail.track(-1),
			ub_index: trail.track(-1),
			storage: Vec::default(),
		}
	}

	/// Find the the index of the node that contains the value or the node
	/// "before" the value.
	fn find_index(&self, start: u32, direction: SearchDirection, val: IntVal) -> u32 {
		let mut i = start;
		match direction {
			SearchDirection::Increasing => {
				while self[i].has_next && self[self[i].next].val <= val {
					i = self[i].next;
				}
			}
			SearchDirection::Decreasing => {
				while self[i].has_prev && self[self[i].prev].val >= val {
					i = self[i].prev;
				}
			}
		}
		i
	}

	/// Returns `true` if the storage is empty, `false` otherwise.
	fn is_empty(&self) -> bool {
		self.storage.is_empty()
	}

	/// Returns the node with the maximum [`OrderNode::val`] present in the
	/// storage, or [`None`] if the storage is empty.
	fn max(&self) -> Option<&OrderNode> {
		if self.is_empty() {
			None
		} else {
			Some(&self[self.max_index])
		}
	}

	/// Returns the node with the minimum [`OrderNode::val`] present in the
	/// storage, or [`None`] if the storage is empty.
	fn min(&self) -> Option<&OrderNode> {
		if self.is_empty() {
			None
		} else {
			Some(&self[self.min_index])
		}
	}
}

impl Index<u32> for LazyOrderStorage {
	type Output = OrderNode;

	fn index(&self, index: u32) -> &Self::Output {
		&self.storage[index as usize]
	}
}

impl IndexMut<u32> for LazyOrderStorage {
	fn index_mut(&mut self, index: u32) -> &mut Self::Output {
		&mut self.storage[index as usize]
	}
}

impl OrderEntry<'_> {
	/// Forward the entry to the entry for next value in the domain.
	///
	/// Note that it is assumed that a next value exists in the domain, and this
	/// method will panic otherwise.
	fn next_value(self) -> Self {
		match self {
			OrderEntry::Eager(vars, offset) => OrderEntry::Eager(vars, offset + 1),
			OrderEntry::Occupied {
				storage,
				index,
				mut range_iter,
			} => {
				let next = storage[index].val + 1;
				let next = if range_iter.peek().unwrap().contains(&next) {
					next
				} else {
					range_iter.next().unwrap();
					*range_iter.peek().unwrap().start()
				};
				let next_index = storage[index].next;
				if storage[index].has_next && storage[next_index].val == next {
					OrderEntry::Occupied {
						storage,
						index: next_index,
						range_iter,
					}
				} else {
					OrderEntry::Vacant {
						storage,
						prev_index: index as IntVal,
						range_iter,
						val: next,
					}
				}
			}
			OrderEntry::Vacant {
				storage,
				prev_index,
				mut range_iter,
				val,
			} => {
				let next = val + 1;
				let next = if range_iter.peek().unwrap().contains(&next) {
					next
				} else {
					range_iter.next().unwrap();
					*range_iter.peek().unwrap().start()
				};
				if prev_index >= 0
					&& storage[prev_index as u32].has_next
					&& storage[storage[prev_index as u32].next].val == next
				{
					OrderEntry::Occupied {
						index: storage[prev_index as u32].next,
						storage,
						range_iter,
					}
				} else if !storage.is_empty() && storage.min().unwrap().val == next {
					OrderEntry::Occupied {
						index: storage.min_index,
						storage,
						range_iter,
					}
				} else {
					OrderEntry::Vacant {
						storage,
						prev_index,
						range_iter,
						val: next,
					}
				}
			}
		}
	}
	/// Extract the [`RawVar`] if the entry is occupied, or insert a new
	/// variable using the given function.
	///
	/// Note that the function is called with the integer value `i`, where the
	/// variable will represent `< i`, the previous variable before `i` and the
	/// variable after `i`, if they exist.
	fn or_insert_with(
		self,
		f: impl FnOnce(IntVal, Option<RawVar>, Option<RawVar>) -> RawVar,
	) -> (Self, RawVar) {
		match self {
			OrderEntry::Eager(vars, offset) => {
				// Lookup corresponding variable
				debug_assert!(
					offset < vars.len(),
					"var range offset, {}, must be in [0, {})",
					offset,
					vars.len(),
				);
				(self, vars.index(offset))
			}
			OrderEntry::Occupied {
				storage,
				index,
				range_iter,
			} => {
				let var = storage[index].var;
				(
					OrderEntry::Occupied {
						storage,
						index,
						range_iter,
					},
					var,
				)
			}
			OrderEntry::Vacant {
				storage,
				prev_index,
				mut range_iter,
				val,
			} => {
				// Determine the previous and next node
				let (prev, next) = if prev_index >= 0 {
					let prev = prev_index as u32;
					let next = if storage[prev].has_next {
						Some(storage[prev].next)
					} else {
						None
					};
					(Some(prev), next)
				} else if !storage.is_empty() {
					(None, Some(storage.min_index))
				} else {
					(None, None)
				};
				// Value should have been resolved and now be in the domain
				debug_assert!(range_iter.peek().unwrap().contains(&val));
				// Call function and insert new node
				let var = f(
					val,
					prev.map(|i| storage[i].var),
					next.map(|i| storage[i].var),
				);
				storage.storage.push(OrderNode {
					val,
					var,
					has_prev: prev.is_some(),
					prev: prev.unwrap_or(0),
					has_next: next.is_some(),
					next: next.unwrap_or(0),
				});
				let index = (storage.storage.len() - 1) as u32;
				if let Some(prev) = prev {
					debug_assert!(storage[prev].val < storage.storage.last().unwrap().val);
					storage[prev].has_next = true;
					storage[prev].next = index;
				} else {
					storage.min_index = index;
				}
				if let Some(next) = next {
					debug_assert!(storage[next].val > storage.storage.last().unwrap().val);
					storage[next].has_prev = true;
					storage[next].prev = index;
				} else {
					storage.max_index = index;
				}

				// Return the new entry
				(
					OrderEntry::Occupied {
						index: storage.storage.len() as u32 - 1,
						storage,
						range_iter,
					},
					var,
				)
			}
		}
	}
}

impl OrderStorage {
	/// Locate the position in the [`OrderStorage`] that would be used to store
	/// the representation of the condition `< i`. The method will return a
	/// [`OrderEntry`] object that can be used to access the condition as a
	/// [`RawVar`] if it already exists, or insert a new literal to represent
	/// the condition otherwise. In addition the function returns an `i` and
	/// `j`, such that `i` is the tightest value for which `< i` is equivalent
	/// to `< val` and `j` is the tightest value for which `≥ j` is equivalent
	/// to `≥ val`.
	///
	/// The given `domain` is (in the case of eager creation) used to determine
	/// the offset of the variable in the `VarRange`.
	fn entry<'a>(
		&'a mut self,
		domain: &'a RangeList<IntVal>,
		val: IntVal,
	) -> (OrderEntry<'a>, IntVal, IntVal) {
		match self {
			OrderStorage::Eager { storage, .. } => {
				let DomainLocation {
					less_val,
					greater_eq_val: val,
					offset,
					..
				} = Self::resolve_val::<1>(domain, val);
				let entry = OrderEntry::Eager(storage, offset[0]);
				(entry, less_val, val)
			}
			OrderStorage::Lazy(storage) => {
				let DomainLocation {
					less_val,
					greater_eq_val: val,
					range_iter,
					..
				} = Self::resolve_val::<0>(domain, val);
				let entry = if storage.is_empty() || storage.min().unwrap().val > val {
					OrderEntry::Vacant {
						storage,
						prev_index: -1,
						range_iter,
						val,
					}
				} else if storage.max().unwrap().val < val {
					OrderEntry::Vacant {
						prev_index: storage.max_index as IntVal,
						storage,
						range_iter,
						val,
					}
				} else {
					let i = storage.find_index(storage.min_index, SearchDirection::Increasing, val);
					debug_assert!(storage[i].val <= val);
					if storage[i].val == val {
						OrderEntry::Occupied {
							storage,
							index: i,
							range_iter,
						}
					} else {
						OrderEntry::Vacant {
							storage,
							prev_index: i as IntVal,
							range_iter,
							val,
						}
					}
				};
				(entry, less_val, val)
			}
		}
	}

	/// Return the [`RawVar`] that represent the condition `< val`, or `≥ val`
	/// if negated, if it already exists. In addition the function returns an
	/// `i` and `j`, such that `i` is the tightest value for which `< i` is
	/// equivalent to `< val` and `j` is the tightest value for which `≥ j` is
	/// equivalent to `≥ val`.
	///
	/// The given `domain` is (in the case of eager creation) used to determine
	/// the offset of the variable in the `VarRange`.
	fn find(&self, domain: &RangeList<IntVal>, val: IntVal) -> Option<(RawVar, IntVal, IntVal)> {
		match self {
			OrderStorage::Eager { storage, .. } => {
				let DomainLocation {
					less_val,
					greater_eq_val: val,
					offset,
					..
				} = Self::resolve_val::<1>(domain, val);
				Some((storage.index(offset[0]), less_val, val))
			}
			OrderStorage::Lazy(storage) => {
				let DomainLocation {
					less_val,
					greater_eq_val: val,
					..
				} = Self::resolve_val::<0>(domain, val);
				if storage.is_empty()
					|| storage.min().unwrap().val > val
					|| storage.max().unwrap().val < val
				{
					return None;
				};

				let i = storage.find_index(storage.min_index, SearchDirection::Increasing, val);
				let var = (storage[i].val == val).then(|| storage[i].var)?;
				Some((var, less_val, val))
			}
		}
	}

	/// Returns the lowest integer value `j`, for which `< i` is equivalent to
	/// `< j` in the given `domain. In addition it returns the index of the
	/// range in `domain` in which `j` is located, and calculate the offset of
	/// the representation `< j` in a VarRange when the order literals are
	/// eagerly created.
	#[inline]
	fn resolve_val<const OFFSET: usize>(
		domain: &RangeList<IntVal>,
		val: IntVal,
	) -> DomainLocation<'_, OFFSET> {
		let mut offset = if OFFSET >= 1 { -1 } else { 0 }; // -1 to account for the lower bound
		let mut it = domain.iter().peekable();
		let mut last_val = IntVal::MIN;
		loop {
			let r = it.peek().unwrap();
			if val < *r.start() {
				return DomainLocation {
					less_val: last_val + 1,
					greater_eq_val: *r.start(),
					offset: [offset as usize; OFFSET],
					range_iter: it,
				};
			} else if val <= *r.end() {
				if OFFSET >= 1 {
					offset += val - r.start();
				}
				return DomainLocation {
					less_val: if val == *r.start() { last_val + 1 } else { val },
					greater_eq_val: val,
					offset: [offset as usize; OFFSET],
					range_iter: it,
				};
			} else if OFFSET >= 1 {
				offset += r.end() - r.start() + 1;
			}
			last_val = *it.next().unwrap().end();
		}
	}
}

#[cfg(test)]
mod tests {
	use std::{iter::once, num::NonZeroI32};

	use itertools::Itertools;
	use pindakaas::Lit as RawLit;

	use crate::{
		IntSet, IntVal,
		actions::{IntDecisionActions, IntInspectionActions},
		solver::{
			IntLitMeaning, LiteralStrategy, Solver,
			decision::{Decision, integer::IntDecision},
			view::{View, boolean::BoolView, integer::IntView},
		},
		views::LinearView,
	};

	fn assert_eager_lits_eq(
		iv: &mut IntDecision,
		input: impl IntoIterator<Item = IntLitMeaning>,
		lits: impl IntoIterator<Item = View<bool>>,
		output: impl IntoIterator<Item = IntLitMeaning>,
	) {
		for (req, expected) in input.into_iter().zip_eq(lits.into_iter().zip_eq(output)) {
			let out = iv.try_lit(req).expect("lit must be present");
			assert_eq!(out, expected, "given {req:?}");
			let out = iv.lit(req, |_| panic!("all literals should be eagerly created"));
			assert_eq!(out, expected, "given {req:?}");
			if let BoolView::Lit(l) = out.0.0 {
				assert_eq!(iv.lit_meaning(l), expected.1);
			}
		}
	}

	fn assert_lazy_lits_eq(
		slv: &mut Solver,
		iv: Decision<IntVal>,
		input: impl IntoIterator<Item = IntLitMeaning>,
		lits: impl IntoIterator<Item = View<bool>>,
		output: impl IntoIterator<Item = IntLitMeaning>,
	) {
		for (req, expected) in input.into_iter().zip_eq(lits.into_iter().zip_eq(output)) {
			let bv = iv.lit(slv, req);
			let m = iv.lit_meaning(slv, bv).unwrap_or(req);
			assert_eq!((bv, m), expected, "given {req:?}");

			let v = &mut slv.engine.borrow_mut().state.int_vars[iv.idx()];
			let out = v.try_lit(req).expect("lit must be present");
			assert_eq!(out, expected, "given {req:?}");
		}
	}

	#[test]
	fn eager_continuous_lits() {
		use IntLitMeaning::*;

		let mut slv: Solver = Solver::default();
		let a = slv
			.new_int_decision(1..=4)
			.order_literals(LiteralStrategy::Eager)
			.direct_literals(LiteralStrategy::Eager)
			.view();
		let IntView::Linear(LinearView { var: a, .. }) = a.0 else {
			unreachable!()
		};
		let a = &mut slv.engine.borrow_mut().state.int_vars[a.idx()];
		assert_eager_lits_eq(
			a,
			(0..=6).map(Less),
			vec![false.into(); 2]
				.into_iter()
				.chain(vec![1, 2, 3].into_iter().map(into_lit))
				.chain(vec![true.into(); 2]),
			(0..=6).map(Less),
		);
		assert_eager_lits_eq(
			a,
			(0..=6).map(GreaterEq),
			vec![true.into(); 2]
				.into_iter()
				.chain(vec![-1, -2, -3].into_iter().map(into_lit))
				.chain(vec![false.into(); 2]),
			(0..=6).map(GreaterEq),
		);
		assert_eager_lits_eq(
			a,
			(0..=6).map(Eq),
			once(false.into())
				.chain(vec![1, 4, 5, -3].into_iter().map(into_lit))
				.chain(vec![false.into(); 2]),
			vec![Eq(0), Less(2), Eq(2), Eq(3), GreaterEq(4), Eq(5), Eq(6)],
		);
		assert_eager_lits_eq(
			a,
			(0..=6).map(NotEq),
			once(true.into())
				.chain(vec![-1, -4, -5, 3].into_iter().map(into_lit))
				.chain(vec![true.into(); 2]),
			vec![
				NotEq(0),
				GreaterEq(2),
				NotEq(2),
				NotEq(3),
				Less(4),
				NotEq(5),
				NotEq(6),
			],
		);
	}

	#[test]
	fn eager_gaps_lits() {
		use IntLitMeaning::*;

		let mut slv: Solver = Solver::default();
		let a = slv
			.new_int_decision(IntSet::from_iter([1..=3, 8..=10]))
			.order_literals(LiteralStrategy::Eager)
			.direct_literals(LiteralStrategy::Eager)
			.view();
		let IntView::Linear(LinearView { var: a, .. }) = a.0 else {
			unreachable!()
		};
		let a = &mut slv.engine.borrow_mut().state.int_vars[a.idx()];
		assert_eager_lits_eq(
			a,
			(2..=10).map(Less),
			vec![1, 2, 3, 3, 3, 3, 3, 4, 5].into_iter().map(into_lit),
			vec![
				Less(2),
				Less(3),
				Less(4),
				Less(4),
				Less(4),
				Less(4),
				Less(4),
				Less(9),
				Less(10),
			],
		);
		assert_eager_lits_eq(
			a,
			(2..=10).map(GreaterEq),
			vec![-1, -2, -3, -3, -3, -3, -3, -4, -5]
				.into_iter()
				.map(into_lit),
			vec![
				GreaterEq(2),
				GreaterEq(3),
				GreaterEq(8),
				GreaterEq(8),
				GreaterEq(8),
				GreaterEq(8),
				GreaterEq(8),
				GreaterEq(9),
				GreaterEq(10),
			],
		);
		assert_eager_lits_eq(
			a,
			(1..=10).map(Eq),
			vec![1, 6, 7]
				.into_iter()
				.map(into_lit)
				.chain(vec![false.into(); 4])
				.chain(vec![8, 9, -5].into_iter().map(into_lit)),
			once(Less(2))
				.chain((2..=9).map(Eq))
				.chain(once(GreaterEq(10))),
		);
		assert_eager_lits_eq(
			a,
			(1..=10).map(NotEq),
			vec![-1, -6, -7]
				.into_iter()
				.map(into_lit)
				.chain(vec![true.into(); 4])
				.chain(vec![-8, -9, 5].into_iter().map(into_lit)),
			once(GreaterEq(2))
				.chain((2..=9).map(NotEq))
				.chain(once(Less(10))),
		);
	}

	fn into_lit(i: i32) -> View<bool> {
		Decision(RawLit::from_raw(NonZeroI32::new(i).unwrap())).into()
	}

	#[test]
	fn lazy_gaps_lits() {
		use IntLitMeaning::*;

		let mut slv: Solver = Solver::default();
		let a = slv
			.new_int_decision(IntSet::from_iter([1..=3, 8..=10]))
			.view();
		let IntView::Linear(LinearView { var: a, .. }) = a.0 else {
			unreachable!()
		};
		assert_lazy_lits_eq(
			&mut slv,
			a,
			(2..=10).map(Less),
			vec![1, 2, 3, 3, 3, 3, 3, 4, 5].into_iter().map(into_lit),
			vec![
				Less(2),
				Less(3),
				Less(4),
				Less(4),
				Less(4),
				Less(4),
				Less(4),
				Less(9),
				Less(10),
			],
		);
		assert_lazy_lits_eq(
			&mut slv,
			a,
			(2..=10).map(GreaterEq),
			vec![-1, -2, -3, -3, -3, -3, -3, -4, -5]
				.into_iter()
				.map(into_lit),
			vec![
				GreaterEq(2),
				GreaterEq(3),
				GreaterEq(8),
				GreaterEq(8),
				GreaterEq(8),
				GreaterEq(8),
				GreaterEq(8),
				GreaterEq(9),
				GreaterEq(10),
			],
		);
		assert_lazy_lits_eq(
			&mut slv,
			a,
			(1..=10).map(Eq),
			vec![1, 6, 7]
				.into_iter()
				.map(into_lit)
				.chain(vec![false.into(); 4])
				.chain(vec![8, 9, -5].into_iter().map(into_lit)),
			once(Less(2))
				.chain((2..=9).map(Eq))
				.chain(once(GreaterEq(10))),
		);
		assert_lazy_lits_eq(
			&mut slv,
			a,
			(1..=10).map(NotEq),
			vec![-1, -6, -7]
				.into_iter()
				.map(into_lit)
				.chain(vec![true.into(); 4])
				.chain(vec![-8, -9, 5].into_iter().map(into_lit)),
			once(GreaterEq(2))
				.chain((2..=9).map(NotEq))
				.chain(once(Less(10))),
		);
	}
}