1use std::cell::RefCell;
23use std::hash::Hash;
24use std::rc::Rc;
25
26pub type Nat = u64;
28pub type Int = i64;
30pub type Real = f64;
32pub type Text = String;
34pub type Bool = bool;
36pub type Unit = ();
38pub type Char = char;
40pub type Byte = u8;
42
43#[derive(Debug)]
49pub struct LogosSeq<T>(pub Rc<RefCell<Vec<T>>>);
50
51impl<T> LogosSeq<T> {
52 pub fn new() -> Self {
53 Self(Rc::new(RefCell::new(Vec::new())))
54 }
55
56 pub fn from_vec(v: Vec<T>) -> Self {
57 Self(Rc::new(RefCell::new(v)))
58 }
59
60 pub fn with_capacity(cap: usize) -> Self {
61 Self(Rc::new(RefCell::new(Vec::with_capacity(cap))))
62 }
63
64 pub fn push(&self, value: T) {
65 self.0.borrow_mut().push(value);
66 }
67
68 pub fn pop(&self) -> Option<T> {
69 self.0.borrow_mut().pop()
70 }
71
72 pub fn len(&self) -> usize {
73 self.0.borrow().len()
74 }
75
76 pub fn is_empty(&self) -> bool {
77 self.0.borrow().is_empty()
78 }
79
80 pub fn remove(&self, index: usize) -> T {
81 self.0.borrow_mut().remove(index)
82 }
83
84 pub fn borrow(&self) -> std::cell::Ref<'_, Vec<T>> {
85 self.0.borrow()
86 }
87
88 pub fn borrow_mut(&self) -> std::cell::RefMut<'_, Vec<T>> {
89 self.0.borrow_mut()
90 }
91}
92
93pub trait FillClone {
98 fn fill_clone(&self) -> Self;
99}
100
101macro_rules! fill_by_clone {
102 ($($t:ty),* $(,)?) => {
103 $(impl FillClone for $t {
104 #[inline]
105 fn fill_clone(&self) -> Self {
106 self.clone()
107 }
108 })*
109 };
110}
111
112fill_by_clone!(i8, i16, i32, i64, i128, u8, u16, u32, u64, usize, f32, f64, bool, char, String);
113
114impl<T: FillClone> FillClone for LogosSeq<T> {
115 fn fill_clone(&self) -> Self {
116 Self(Rc::new(RefCell::new(
117 self.0.borrow().iter().map(|e| e.fill_clone()).collect(),
118 )))
119 }
120}
121
122impl<K: Clone + Eq + Hash, V: FillClone> FillClone for LogosMap<K, V> {
123 fn fill_clone(&self) -> Self {
124 Self(Rc::new(RefCell::new(
125 self.0
126 .borrow()
127 .iter()
128 .map(|(k, v)| (k.clone(), v.fill_clone()))
129 .collect(),
130 )))
131 }
132}
133
134impl<T: Clone> LogosSeq<T> {
135 pub fn deep_clone(&self) -> Self {
136 Self(Rc::new(RefCell::new(self.0.borrow().clone())))
137 }
138
139 pub fn to_vec(&self) -> Vec<T> {
140 self.0.borrow().clone()
141 }
142
143 pub fn extend_from_slice(&self, other: &[T]) {
144 self.0.borrow_mut().extend_from_slice(other);
145 }
146
147 pub fn iter(&self) -> LogosSeqIter<T> {
148 LogosSeqIter {
149 data: self.to_vec(),
150 pos: 0,
151 }
152 }
153}
154
155pub struct LogosSeqIter<T> {
156 data: Vec<T>,
157 pos: usize,
158}
159
160impl<T: Clone> Iterator for LogosSeqIter<T> {
161 type Item = T;
162 fn next(&mut self) -> Option<T> {
163 if self.pos < self.data.len() {
164 let val = self.data[self.pos].clone();
165 self.pos += 1;
166 Some(val)
167 } else {
168 None
169 }
170 }
171}
172
173impl<T: Ord> LogosSeq<T> {
174 pub fn sort(&self) {
175 self.0.borrow_mut().sort();
176 }
177}
178
179impl<T> LogosSeq<T> {
180 pub fn reverse(&self) {
181 self.0.borrow_mut().reverse();
182 }
183}
184
185pub fn value_semantics_enabled() -> bool {
191 use std::sync::OnceLock;
192 static ON: OnceLock<bool> = OnceLock::new();
193 *ON.get_or_init(|| std::env::var("LOGOS_VALUE_SEMANTICS").as_deref() != Ok("0"))
196}
197
198impl<T: Clone> Clone for LogosSeq<T> {
199 fn clone(&self) -> Self {
200 Self(Rc::clone(&self.0))
208 }
209}
210
211impl<T: Clone> LogosSeq<T> {
212 #[inline]
219 pub fn cow(&mut self) {
220 if Rc::strong_count(&self.0) > 1 {
221 let cloned = self.0.borrow().clone();
224 self.0 = Rc::new(RefCell::new(cloned));
225 }
226 }
227}
228
229pub trait VecCowNoop {
238 #[inline]
239 fn cow(&mut self) {}
240}
241impl<T> VecCowNoop for Vec<T> {}
242
243impl<T: Clone> LogosSeq<LogosSeq<T>> {
244 #[inline]
252 pub fn set_nested(&self, k: i64, i: i64, v: T) {
253 use crate::LogosItems;
254 let mut outer = self.borrow_mut();
255 let row = outer.logos_item_mut(k);
256 row.cow();
257 *row.borrow_mut().logos_item_mut(i) = v;
258 }
259}
260
261impl<T> Default for LogosSeq<T> {
262 fn default() -> Self {
263 Self::new()
264 }
265}
266
267impl<T: PartialEq> PartialEq for LogosSeq<T> {
268 fn eq(&self, other: &Self) -> bool {
269 *self.0.borrow() == *other.0.borrow()
270 }
271}
272
273impl<T: std::fmt::Display> std::fmt::Display for LogosSeq<T> {
274 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275 let inner = self.0.borrow();
276 write!(f, "[")?;
277 for (i, item) in inner.iter().enumerate() {
278 if i > 0 {
279 write!(f, ", ")?;
280 }
281 write!(f, "{}", item)?;
282 }
283 write!(f, "]")
284 }
285}
286
287impl<T> From<Vec<T>> for LogosSeq<T> {
288 fn from(v: Vec<T>) -> Self {
289 Self::from_vec(v)
290 }
291}
292
293impl<T: serde::Serialize> serde::Serialize for LogosSeq<T> {
294 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
295 self.0.borrow().serialize(serializer)
296 }
297}
298
299impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for LogosSeq<T> {
300 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
301 let vec = Vec::<T>::deserialize(deserializer)?;
302 Ok(Self::from_vec(vec))
303 }
304}
305
306impl<T: PartialEq> LogosContains<T> for LogosSeq<T> {
307 #[inline(always)]
308 fn logos_contains(&self, value: &T) -> bool {
309 self.0.borrow().contains(value)
310 }
311}
312
313impl<T: Clone> IntoIterator for LogosSeq<T> {
314 type Item = T;
315 type IntoIter = std::vec::IntoIter<T>;
316
317 fn into_iter(self) -> Self::IntoIter {
318 self.to_vec().into_iter()
319 }
320}
321
322pub type FxIndexMap<K, V> =
327 indexmap::IndexMap<K, V, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
328
329#[derive(Debug)]
335pub struct LogosMap<K, V>(pub Rc<RefCell<FxIndexMap<K, V>>>);
336
337impl<K: Eq + Hash, V> LogosMap<K, V> {
338 pub fn new() -> Self {
339 Self(Rc::new(RefCell::new(FxIndexMap::default())))
340 }
341
342 pub fn with_capacity(cap: usize) -> Self {
343 Self(Rc::new(RefCell::new(FxIndexMap::with_capacity_and_hasher(
344 cap,
345 Default::default(),
346 ))))
347 }
348
349 pub fn from_map(m: FxIndexMap<K, V>) -> Self {
350 Self(Rc::new(RefCell::new(m)))
351 }
352
353 pub fn insert(&self, key: K, value: V) -> Option<V> {
354 self.0.borrow_mut().insert(key, value)
355 }
356
357 pub fn remove(&self, key: &K) -> Option<V> {
360 self.0.borrow_mut().shift_remove(key)
361 }
362
363 pub fn len(&self) -> usize {
364 self.0.borrow().len()
365 }
366
367 pub fn is_empty(&self) -> bool {
368 self.0.borrow().is_empty()
369 }
370
371 pub fn contains_key(&self, key: &K) -> bool {
372 self.0.borrow().contains_key(key)
373 }
374
375 pub fn borrow(&self) -> std::cell::Ref<'_, FxIndexMap<K, V>> {
376 self.0.borrow()
377 }
378
379 pub fn borrow_mut(&self) -> std::cell::RefMut<'_, FxIndexMap<K, V>> {
380 self.0.borrow_mut()
381 }
382}
383
384impl<K: Eq + Hash + Clone, V: Clone> LogosMap<K, V> {
385 pub fn deep_clone(&self) -> Self {
386 Self(Rc::new(RefCell::new(self.0.borrow().clone())))
387 }
388
389 pub fn get(&self, key: &K) -> Option<V> {
390 self.0.borrow().get(key).cloned()
391 }
392
393 pub fn values(&self) -> Vec<V> {
394 self.0.borrow().values().cloned().collect()
395 }
396
397 pub fn keys(&self) -> Vec<K> {
398 self.0.borrow().keys().cloned().collect()
399 }
400}
401
402impl<K: Clone, V: Clone> Clone for LogosMap<K, V> {
403 fn clone(&self) -> Self {
404 Self(Rc::clone(&self.0))
408 }
409}
410
411impl<K: Clone, V: Clone> LogosMap<K, V> {
412 #[inline]
415 pub fn cow(&mut self) {
416 if Rc::strong_count(&self.0) > 1 {
417 let cloned = self.0.borrow().clone();
420 self.0 = Rc::new(RefCell::new(cloned));
421 }
422 }
423}
424
425impl<K: Eq + Hash, V> Default for LogosMap<K, V> {
426 fn default() -> Self {
427 Self::new()
428 }
429}
430
431impl<K: PartialEq + Eq + Hash, V: PartialEq> PartialEq for LogosMap<K, V> {
432 fn eq(&self, other: &Self) -> bool {
433 *self.0.borrow() == *other.0.borrow()
434 }
435}
436
437impl<K: std::fmt::Display + Eq + Hash, V: std::fmt::Display> std::fmt::Display for LogosMap<K, V> {
438 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
439 let inner = self.0.borrow();
440 write!(f, "{{")?;
441 for (i, (k, v)) in inner.iter().enumerate() {
442 if i > 0 {
443 write!(f, ", ")?;
444 }
445 write!(f, "{}: {}", k, v)?;
446 }
447 write!(f, "}}")
448 }
449}
450
451impl<K: serde::Serialize + Eq + Hash, V: serde::Serialize> serde::Serialize for LogosMap<K, V> {
452 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
453 self.0.borrow().serialize(serializer)
454 }
455}
456
457impl<'de, K: serde::Deserialize<'de> + Eq + Hash, V: serde::Deserialize<'de>>
458 serde::Deserialize<'de> for LogosMap<K, V>
459{
460 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
461 let map = FxIndexMap::<K, V>::deserialize(deserializer)?;
462 Ok(Self::from_map(map))
463 }
464}
465
466impl<K: Clone, V: Clone> IntoIterator for LogosMap<K, V> {
471 type Item = (K, V);
472 type IntoIter = std::vec::IntoIter<(K, V)>;
473
474 fn into_iter(self) -> Self::IntoIter {
475 let entries: Vec<(K, V)> = self
476 .0
477 .borrow()
478 .iter()
479 .map(|(k, v)| (k.clone(), v.clone()))
480 .collect();
481 entries.into_iter()
482 }
483}
484
485impl<K: Eq + Hash, V> LogosContains<K> for LogosMap<K, V> {
486 #[inline(always)]
487 fn logos_contains(&self, key: &K) -> bool {
488 self.0.borrow().contains_key(key)
489 }
490}
491
492const INT_TABLE_MAX_LOAD: (usize, usize) = (1, 2);
497
498fn int_table_slots(cap: usize) -> usize {
500 let (num, den) = INT_TABLE_MAX_LOAD;
501 (cap.saturating_mul(den) / num + 1).next_power_of_two().max(8)
502}
503
504#[inline(always)]
508fn fib_slot(key: u64, shift: u32) -> usize {
509 (key.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> shift) as usize
510}
511
512fn int_table_full(len: usize, slots: usize) -> bool {
514 let (num, den) = INT_TABLE_MAX_LOAD;
515 (len + 1) * den > slots * num
516}
517
518#[derive(Debug, Clone)]
535pub struct LogosI64Map {
536 entries: Vec<[i64; 2]>,
541 mask: usize,
542 shift: u32,
544 len: usize,
545 has_zero_key: bool,
546 zero_key_val: i64,
547}
548
549impl LogosI64Map {
550 const EMPTY: i64 = 0;
551
552 pub fn new() -> Self {
553 Self {
554 entries: Vec::new(),
555 mask: 0,
556 shift: 64,
557 len: 0,
558 has_zero_key: false,
559 zero_key_val: 0,
560 }
561 }
562
563 pub fn with_capacity(cap: usize) -> Self {
564 let mut m = Self::new();
565 if cap > 0 {
566 let slots = int_table_slots(cap);
569 m.entries = vec![[Self::EMPTY, 0]; slots];
572 m.mask = slots - 1;
573 m.shift = 64 - slots.trailing_zeros();
574 }
575 m
576 }
577
578 #[inline]
581 fn table_len(&self) -> usize {
582 self.len - self.has_zero_key as usize
583 }
584
585 #[inline(always)]
588 fn assume_table_invariant(&self) {
589 unsafe {
590 std::hint::assert_unchecked(self.mask + 1 == self.entries.len());
591 }
592 }
593
594 #[inline]
595 fn slot(&self, key: i64) -> usize {
596 fib_slot(key as u64, self.shift)
597 }
598
599 #[inline]
600 pub fn insert(&mut self, key: i64, value: i64) {
601 if key == Self::EMPTY {
602 if !self.has_zero_key {
603 self.has_zero_key = true;
604 self.len += 1;
605 }
606 self.zero_key_val = value;
607 return;
608 }
609 if self.mask == 0 || int_table_full(self.table_len(), self.mask + 1) {
610 self.grow();
611 }
612 self.assume_table_invariant();
613 let mut i = self.slot(key);
614 loop {
615 let k = self.entries[i][0];
616 if k == Self::EMPTY {
617 self.entries[i] = [key, value];
618 self.len += 1;
619 return;
620 }
621 if k == key {
622 self.entries[i][1] = value;
623 return;
624 }
625 i = (i + 1) & self.mask;
626 }
627 }
628
629 #[cold]
630 #[inline(never)]
631 fn grow(&mut self) {
632 let new_slots = if self.mask == 0 {
633 8
634 } else {
635 (self.mask + 1) * 2
636 };
637 let old = std::mem::replace(&mut self.entries, vec![[Self::EMPTY, 0]; new_slots]);
638 self.mask = new_slots - 1;
639 self.shift = 64 - new_slots.trailing_zeros();
640 self.assume_table_invariant();
641 for &[k, v] in old.iter() {
642 if k != Self::EMPTY {
643 let mut i = self.slot(k);
644 while self.entries[i][0] != Self::EMPTY {
645 i = (i + 1) & self.mask;
646 }
647 self.entries[i] = [k, v];
648 }
649 }
650 }
651
652 #[inline]
653 pub fn get(&self, key: &i64) -> Option<i64> {
654 let key = *key;
655 if key == Self::EMPTY {
656 return if self.has_zero_key {
657 Some(self.zero_key_val)
658 } else {
659 None
660 };
661 }
662 if self.mask == 0 {
663 return None;
664 }
665 self.assume_table_invariant();
666 let mut i = self.slot(key);
667 loop {
668 let [k, v] = self.entries[i];
669 if k == key {
670 return Some(v);
671 }
672 if k == Self::EMPTY {
673 return None;
674 }
675 i = (i + 1) & self.mask;
676 }
677 }
678
679 #[inline]
680 pub fn contains_key(&self, key: &i64) -> bool {
681 self.get(key).is_some()
682 }
683
684 pub fn len(&self) -> usize {
685 self.len
686 }
687
688 pub fn is_empty(&self) -> bool {
689 self.len == 0
690 }
691}
692
693impl Default for LogosI64Map {
694 fn default() -> Self {
695 Self::new()
696 }
697}
698
699impl LogosContains<i64> for LogosI64Map {
700 #[inline(always)]
701 fn logos_contains(&self, key: &i64) -> bool {
702 self.get(key).is_some()
703 }
704}
705
706#[derive(Debug, Clone, Default)]
714pub struct LogosBits {
715 words: Vec<u64>,
717 len: usize,
718}
719
720impl LogosBits {
721 pub fn new() -> Self {
722 Self::default()
723 }
724
725 pub fn with_capacity(items: usize) -> Self {
727 LogosBits {
728 words: Vec::with_capacity(items.div_ceil(64)),
729 len: 0,
730 }
731 }
732
733 pub fn filled(len: usize, value: bool) -> Self {
735 let mut words = vec![if value { u64::MAX } else { 0 }; len.div_ceil(64)];
736 if value && len % 64 != 0 {
737 if let Some(last) = words.last_mut() {
738 *last = (1u64 << (len % 64)) - 1;
739 }
740 }
741 LogosBits { words, len }
742 }
743
744 #[inline(always)]
745 pub fn len(&self) -> usize {
746 self.len
747 }
748
749 #[inline(always)]
750 pub fn is_empty(&self) -> bool {
751 self.len == 0
752 }
753
754 #[inline]
755 pub fn push(&mut self, value: bool) {
756 if self.len % 64 == 0 {
757 self.words.push(0);
758 }
759 let at = self.len;
760 self.len += 1;
761 unsafe { self.set_unchecked(at, value) }
763 }
764
765 #[inline]
767 pub fn item(&self, index: i64) -> bool {
768 let at = crate::resolve_logos_index(index, self.len);
769 unsafe { self.get_unchecked(at) }
771 }
772
773 #[inline]
775 pub fn set_item(&mut self, index: i64, value: bool) {
776 let at = crate::resolve_logos_index(index, self.len);
777 unsafe { self.set_unchecked(at, value) }
779 }
780
781 #[inline(always)]
786 pub unsafe fn get_unchecked(&self, offset: usize) -> bool {
787 debug_assert!(offset < self.len);
788 (*self.words.get_unchecked(offset / 64) >> (offset % 64)) & 1 == 1
789 }
790
791 #[inline(always)]
796 pub unsafe fn set_unchecked(&mut self, offset: usize, value: bool) {
797 debug_assert!(offset < self.len);
798 let word = self.words.get_unchecked_mut(offset / 64);
799 let bit = 1u64 << (offset % 64);
800 *word = (*word & !bit) | ((value as u64) << (offset % 64));
801 }
802
803 #[inline(always)]
808 pub unsafe fn set_true_unchecked(&mut self, offset: usize) {
809 debug_assert!(offset < self.len);
810 *self.words.get_unchecked_mut(offset / 64) |= 1u64 << (offset % 64);
811 }
812
813 #[inline]
822 pub unsafe fn fill_stride_unchecked(&mut self, first: usize, count: usize, step: usize, value: bool) {
823 debug_assert!(step >= 1);
824 debug_assert!(count == 0 || first + (count - 1) * step < self.len);
825 if step >= 64 || count < 8 {
826 let mut at = first;
827 for _ in 0..count {
828 let word = self.words.get_unchecked_mut(at / 64);
829 let bit = 1u64 << (at % 64);
830 *word = if value { *word | bit } else { *word & !bit };
831 at += step;
832 }
833 } else {
834 self.fill_stride_words(first, count, step, value);
835 }
836 }
837
838 #[inline(never)]
847 pub unsafe fn fill_stride_through_unchecked(
848 &mut self,
849 first: usize,
850 through: usize,
851 step: usize,
852 value: bool,
853 ) -> usize {
854 debug_assert!(step >= 1 && first <= through);
855 let more = (through - first) / step;
856 self.fill_stride_unchecked(first, more + 1, step, value);
857 more
858 }
859
860 #[inline(never)]
867 unsafe fn fill_stride_words(&mut self, first: usize, count: usize, step: usize, value: bool) {
868 let last = first + (count - 1) * step;
869 let words = self.words.as_mut_ptr();
870 let store = |w: usize, mask: u64| {
871 let word = words.add(w);
872 *word = if value { *word | mask } else { *word & !mask };
873 };
874 let mut pattern = 0u64;
875 let mut k = 0;
876 while k < 64 {
877 pattern |= 1u64 << k;
878 k += step;
879 }
880 let back = 64 % step;
881 let (first_word, last_word) = (first / 64, last / 64);
882 let through_last = u64::MAX >> (63 - last % 64);
883 let mut phase = first % 64;
884 if first_word == last_word {
885 store(first_word, (pattern << phase) & through_last);
886 return;
887 }
888 store(first_word, pattern << phase);
889 phase = (phase + step - back) % step;
890 for w in first_word + 1..last_word {
891 store(w, pattern << phase);
892 phase = if phase >= back { phase - back } else { phase + step - back };
893 }
894 store(last_word, (pattern << phase) & through_last);
895 }
896
897 pub fn iter(&self) -> impl Iterator<Item = bool> + '_ {
899 (0..self.len).map(move |k| unsafe { self.get_unchecked(k) })
901 }
902}
903
904impl PartialEq for LogosBits {
905 fn eq(&self, other: &Self) -> bool {
906 self.len == other.len && self.words == other.words
907 }
908}
909
910impl Eq for LogosBits {}
911
912#[derive(Debug, Clone)]
925pub struct LogosI64Set {
926 keys: Vec<i64>,
927 mask: usize,
928 shift: u32,
930 len: usize,
931 has_zero_key: bool,
932}
933
934impl LogosI64Set {
935 const EMPTY: i64 = 0;
936
937 pub fn new() -> Self {
938 Self {
939 keys: Vec::new(),
940 mask: 0,
941 shift: 64,
942 len: 0,
943 has_zero_key: false,
944 }
945 }
946
947 pub fn with_capacity(cap: usize) -> Self {
948 let mut s = Self::new();
949 if cap > 0 {
950 let slots = int_table_slots(cap);
951 s.keys = vec![Self::EMPTY; slots];
954 s.mask = slots - 1;
955 s.shift = 64 - slots.trailing_zeros();
956 }
957 s
958 }
959
960 #[inline]
961 fn table_len(&self) -> usize {
962 self.len - self.has_zero_key as usize
963 }
964
965 #[inline(always)]
971 fn assume_table_invariant(&self) {
972 unsafe {
973 std::hint::assert_unchecked(self.mask + 1 == self.keys.len());
974 }
975 }
976
977 #[inline]
978 fn slot(&self, key: i64) -> usize {
979 fib_slot(key as u64, self.shift)
980 }
981
982 #[inline]
986 pub fn insert(&mut self, key: i64, _value: i64) {
987 if key == Self::EMPTY {
988 if !self.has_zero_key {
989 self.has_zero_key = true;
990 self.len += 1;
991 }
992 return;
993 }
994 if self.mask == 0 || int_table_full(self.table_len(), self.mask + 1) {
995 self.grow();
996 }
997 self.assume_table_invariant();
998 let mut i = self.slot(key);
999 loop {
1000 let k = self.keys[i];
1001 if k == Self::EMPTY {
1002 self.keys[i] = key;
1003 self.len += 1;
1004 return;
1005 }
1006 if k == key {
1007 return;
1008 }
1009 i = (i + 1) & self.mask;
1010 }
1011 }
1012
1013 #[cold]
1014 #[inline(never)]
1015 fn grow(&mut self) {
1016 let new_slots = if self.mask == 0 {
1017 8
1018 } else {
1019 (self.mask + 1) * 2
1020 };
1021 let old_keys = std::mem::replace(&mut self.keys, vec![Self::EMPTY; new_slots]);
1022 self.mask = new_slots - 1;
1023 self.shift = 64 - new_slots.trailing_zeros();
1024 self.assume_table_invariant();
1025 for &k in old_keys.iter() {
1026 if k != Self::EMPTY {
1027 let mut i = self.slot(k);
1028 while self.keys[i] != Self::EMPTY {
1029 i = (i + 1) & self.mask;
1030 }
1031 self.keys[i] = k;
1032 }
1033 }
1034 }
1035
1036 #[inline]
1037 pub fn contains_key(&self, key: &i64) -> bool {
1038 let key = *key;
1039 if key == Self::EMPTY {
1040 return self.has_zero_key;
1041 }
1042 if self.mask == 0 {
1043 return false;
1044 }
1045 self.assume_table_invariant();
1046 let mut i = self.slot(key);
1047 loop {
1048 let k = self.keys[i];
1049 if k == key {
1050 return true;
1051 }
1052 if k == Self::EMPTY {
1053 return false;
1054 }
1055 i = (i + 1) & self.mask;
1056 }
1057 }
1058
1059 pub fn len(&self) -> usize {
1060 self.len
1061 }
1062
1063 pub fn is_empty(&self) -> bool {
1064 self.len == 0
1065 }
1066}
1067
1068impl Default for LogosI64Set {
1069 fn default() -> Self {
1070 Self::new()
1071 }
1072}
1073
1074impl LogosContains<i64> for LogosI64Set {
1075 #[inline(always)]
1076 fn logos_contains(&self, key: &i64) -> bool {
1077 self.contains_key(key)
1078 }
1079}
1080
1081#[derive(Debug, Clone)]
1089pub struct LogosI32Map {
1090 entries: Vec<[i32; 2]>,
1091 mask: usize,
1092 shift: u32,
1094 len: usize,
1095 has_zero_key: bool,
1096 zero_key_val: i32,
1097}
1098
1099impl LogosI32Map {
1100 const EMPTY: i32 = 0;
1101
1102 pub fn new() -> Self {
1103 Self {
1104 entries: Vec::new(),
1105 mask: 0,
1106 shift: 64,
1107 len: 0,
1108 has_zero_key: false,
1109 zero_key_val: 0,
1110 }
1111 }
1112
1113 pub fn with_capacity(cap: usize) -> Self {
1114 let mut m = Self::new();
1115 if cap > 0 {
1116 let slots = int_table_slots(cap);
1117 m.entries = vec![[Self::EMPTY, 0]; slots];
1119 m.mask = slots - 1;
1120 m.shift = 64 - slots.trailing_zeros();
1121 }
1122 m
1123 }
1124
1125 #[inline]
1126 fn table_len(&self) -> usize {
1127 self.len - self.has_zero_key as usize
1128 }
1129
1130 #[inline(always)]
1133 fn assume_table_invariant(&self) {
1134 unsafe {
1135 std::hint::assert_unchecked(self.mask + 1 == self.entries.len());
1136 }
1137 }
1138
1139 #[inline]
1140 fn slot(&self, key: i32) -> usize {
1141 fib_slot(key as u32 as u64, self.shift)
1142 }
1143
1144 #[inline]
1145 pub fn insert(&mut self, key: i64, value: i64) {
1146 let key = key as i32;
1147 let value = value as i32;
1148 if key == Self::EMPTY {
1149 if !self.has_zero_key {
1150 self.has_zero_key = true;
1151 self.len += 1;
1152 }
1153 self.zero_key_val = value;
1154 return;
1155 }
1156 if self.mask == 0 || int_table_full(self.table_len(), self.mask + 1) {
1157 self.grow();
1158 }
1159 self.assume_table_invariant();
1160 let mut i = self.slot(key);
1161 loop {
1162 let k = self.entries[i][0];
1163 if k == Self::EMPTY {
1164 self.entries[i] = [key, value];
1165 self.len += 1;
1166 return;
1167 }
1168 if k == key {
1169 self.entries[i][1] = value;
1170 return;
1171 }
1172 i = (i + 1) & self.mask;
1173 }
1174 }
1175
1176 #[cold]
1177 #[inline(never)]
1178 fn grow(&mut self) {
1179 let new_slots = if self.mask == 0 {
1180 8
1181 } else {
1182 (self.mask + 1) * 2
1183 };
1184 let old = std::mem::replace(&mut self.entries, vec![[Self::EMPTY, 0]; new_slots]);
1185 self.mask = new_slots - 1;
1186 self.shift = 64 - new_slots.trailing_zeros();
1187 self.assume_table_invariant();
1188 for &[k, v] in old.iter() {
1189 if k != Self::EMPTY {
1190 let mut i = self.slot(k);
1191 while self.entries[i][0] != Self::EMPTY {
1192 i = (i + 1) & self.mask;
1193 }
1194 self.entries[i] = [k, v];
1195 }
1196 }
1197 }
1198
1199 #[inline]
1200 pub fn get(&self, key: &i64) -> Option<i64> {
1201 let key = *key as i32;
1202 if key == Self::EMPTY {
1203 return if self.has_zero_key {
1204 Some(self.zero_key_val as i64)
1205 } else {
1206 None
1207 };
1208 }
1209 if self.mask == 0 {
1210 return None;
1211 }
1212 self.assume_table_invariant();
1213 let mut i = self.slot(key);
1214 loop {
1215 let [k, v] = self.entries[i];
1216 if k == key {
1217 return Some(v as i64);
1218 }
1219 if k == Self::EMPTY {
1220 return None;
1221 }
1222 i = (i + 1) & self.mask;
1223 }
1224 }
1225
1226 #[inline]
1227 pub fn contains_key(&self, key: &i64) -> bool {
1228 self.get(key).is_some()
1229 }
1230
1231 pub fn len(&self) -> usize {
1232 self.len
1233 }
1234
1235 pub fn is_empty(&self) -> bool {
1236 self.len == 0
1237 }
1238}
1239
1240impl Default for LogosI32Map {
1241 fn default() -> Self {
1242 Self::new()
1243 }
1244}
1245
1246impl LogosContains<i64> for LogosI32Map {
1247 #[inline(always)]
1248 fn logos_contains(&self, key: &i64) -> bool {
1249 self.get(key).is_some()
1250 }
1251}
1252
1253#[derive(Debug, Clone)]
1260pub struct LogosI32Set {
1261 keys: Vec<i32>,
1262 mask: usize,
1263 shift: u32,
1265 len: usize,
1266 has_zero_key: bool,
1267}
1268
1269impl LogosI32Set {
1270 const EMPTY: i32 = 0;
1271
1272 pub fn new() -> Self {
1273 Self {
1274 keys: Vec::new(),
1275 mask: 0,
1276 shift: 64,
1277 len: 0,
1278 has_zero_key: false,
1279 }
1280 }
1281
1282 pub fn with_capacity(cap: usize) -> Self {
1283 let mut s = Self::new();
1284 if cap > 0 {
1285 let slots = int_table_slots(cap);
1286 s.keys = vec![Self::EMPTY; slots];
1287 s.mask = slots - 1;
1288 s.shift = 64 - slots.trailing_zeros();
1289 }
1290 s
1291 }
1292
1293 #[inline]
1294 fn table_len(&self) -> usize {
1295 self.len - self.has_zero_key as usize
1296 }
1297
1298 #[inline(always)]
1301 fn assume_table_invariant(&self) {
1302 unsafe {
1303 std::hint::assert_unchecked(self.mask + 1 == self.keys.len());
1304 }
1305 }
1306
1307 #[inline]
1308 fn slot(&self, key: i32) -> usize {
1309 fib_slot(key as u32 as u64, self.shift)
1310 }
1311
1312 #[inline]
1313 pub fn insert(&mut self, key: i64, _value: i64) {
1314 let key = key as i32;
1315 if key == Self::EMPTY {
1316 if !self.has_zero_key {
1317 self.has_zero_key = true;
1318 self.len += 1;
1319 }
1320 return;
1321 }
1322 if self.mask == 0 || int_table_full(self.table_len(), self.mask + 1) {
1323 self.grow();
1324 }
1325 self.assume_table_invariant();
1326 let mut i = self.slot(key);
1327 loop {
1328 let k = self.keys[i];
1329 if k == Self::EMPTY {
1330 self.keys[i] = key;
1331 self.len += 1;
1332 return;
1333 }
1334 if k == key {
1335 return;
1336 }
1337 i = (i + 1) & self.mask;
1338 }
1339 }
1340
1341 #[cold]
1342 #[inline(never)]
1343 fn grow(&mut self) {
1344 let new_slots = if self.mask == 0 {
1345 8
1346 } else {
1347 (self.mask + 1) * 2
1348 };
1349 let old_keys = std::mem::replace(&mut self.keys, vec![Self::EMPTY; new_slots]);
1350 self.mask = new_slots - 1;
1351 self.shift = 64 - new_slots.trailing_zeros();
1352 self.assume_table_invariant();
1353 for &k in old_keys.iter() {
1354 if k != Self::EMPTY {
1355 let mut i = self.slot(k);
1356 while self.keys[i] != Self::EMPTY {
1357 i = (i + 1) & self.mask;
1358 }
1359 self.keys[i] = k;
1360 }
1361 }
1362 }
1363
1364 #[inline]
1365 pub fn contains_key(&self, key: &i64) -> bool {
1366 let key = *key as i32;
1367 if key == Self::EMPTY {
1368 return self.has_zero_key;
1369 }
1370 if self.mask == 0 {
1371 return false;
1372 }
1373 self.assume_table_invariant();
1374 let mut i = self.slot(key);
1375 loop {
1376 let k = self.keys[i];
1377 if k == key {
1378 return true;
1379 }
1380 if k == Self::EMPTY {
1381 return false;
1382 }
1383 i = (i + 1) & self.mask;
1384 }
1385 }
1386
1387 pub fn len(&self) -> usize {
1388 self.len
1389 }
1390
1391 pub fn is_empty(&self) -> bool {
1392 self.len == 0
1393 }
1394}
1395
1396impl Default for LogosI32Set {
1397 fn default() -> Self {
1398 Self::new()
1399 }
1400}
1401
1402impl LogosContains<i64> for LogosI32Set {
1403 #[inline(always)]
1404 fn logos_contains(&self, key: &i64) -> bool {
1405 self.contains_key(key)
1406 }
1407}
1408
1409#[derive(Debug, Clone)]
1420pub struct LogosDenseI64Map {
1421 data: Vec<i64>,
1424 present: Vec<u64>,
1426 lo: i64,
1429 len: usize,
1430}
1431
1432impl LogosDenseI64Map {
1433 pub fn new() -> Self {
1434 Self {
1435 data: Vec::new(),
1436 present: Vec::new(),
1437 lo: 0,
1438 len: 0,
1439 }
1440 }
1441
1442 pub fn with_capacity(cap: usize) -> Self {
1445 Self::with_bounds(0, cap)
1446 }
1447
1448 pub fn with_bounds(lo: i64, slots: usize) -> Self {
1452 Self {
1453 data: vec![0; slots],
1454 present: vec![0; slots.div_ceil(64)],
1455 lo,
1456 len: 0,
1457 }
1458 }
1459
1460 #[inline]
1461 pub fn insert(&mut self, key: i64, value: i64) {
1462 let idx = (key - self.lo) as usize;
1463 debug_assert!(
1464 key >= self.lo && idx < self.data.len(),
1465 "dense map key {key} outside proven window [{}, {})",
1466 self.lo,
1467 self.lo + self.data.len() as i64
1468 );
1469 let bit = 1u64 << (idx & 63);
1470 let word = &mut self.present[idx >> 6];
1471 if *word & bit == 0 {
1472 *word |= bit;
1473 self.len += 1;
1474 }
1475 self.data[idx] = value;
1476 }
1477
1478 #[inline]
1479 pub fn get(&self, key: &i64) -> Option<i64> {
1480 let idx = (*key - self.lo) as usize;
1481 debug_assert!(
1482 *key >= self.lo && idx < self.data.len(),
1483 "dense map key {key} outside proven window [{}, {})",
1484 self.lo,
1485 self.lo + self.data.len() as i64
1486 );
1487 if self.present[idx >> 6] & (1u64 << (idx & 63)) != 0 {
1488 Some(self.data[idx])
1489 } else {
1490 None
1491 }
1492 }
1493
1494 #[inline]
1495 pub fn contains_key(&self, key: &i64) -> bool {
1496 let idx = (*key - self.lo) as usize;
1497 debug_assert!(*key >= self.lo && idx < self.data.len());
1498 self.present[idx >> 6] & (1u64 << (idx & 63)) != 0
1499 }
1500
1501 pub fn len(&self) -> usize {
1502 self.len
1503 }
1504
1505 pub fn is_empty(&self) -> bool {
1506 self.len == 0
1507 }
1508}
1509
1510impl Default for LogosDenseI64Map {
1511 fn default() -> Self {
1512 Self::new()
1513 }
1514}
1515
1516impl LogosContains<i64> for LogosDenseI64Map {
1517 #[inline(always)]
1518 fn logos_contains(&self, key: &i64) -> bool {
1519 self.contains_key(key)
1520 }
1521}
1522
1523#[derive(Debug, Clone)]
1534pub struct LogosDenseI64MapNoPresence {
1535 data: Vec<i64>,
1536 lo: i64,
1537 len: usize,
1540}
1541
1542impl LogosDenseI64MapNoPresence {
1543 pub fn new() -> Self {
1544 Self {
1545 data: Vec::new(),
1546 lo: 0,
1547 len: 0,
1548 }
1549 }
1550
1551 pub fn with_capacity(cap: usize) -> Self {
1552 Self::with_bounds(0, cap)
1553 }
1554
1555 pub fn with_bounds(lo: i64, slots: usize) -> Self {
1556 Self {
1557 data: vec![0; slots],
1558 lo,
1559 len: 0,
1560 }
1561 }
1562
1563 #[inline]
1564 pub fn insert(&mut self, key: i64, value: i64) {
1565 let idx = (key - self.lo) as usize;
1566 debug_assert!(
1567 key >= self.lo && idx < self.data.len(),
1568 "dense map key {key} outside proven window [{}, {})",
1569 self.lo,
1570 self.lo + self.data.len() as i64
1571 );
1572 self.data[idx] = value;
1573 self.len += 1;
1574 }
1575
1576 #[inline]
1577 pub fn get(&self, key: &i64) -> Option<i64> {
1578 let idx = (*key - self.lo) as usize;
1579 debug_assert!(
1580 *key >= self.lo && idx < self.data.len(),
1581 "dense map key {key} outside proven window [{}, {})",
1582 self.lo,
1583 self.lo + self.data.len() as i64
1584 );
1585 Some(self.data[idx])
1586 }
1587
1588 pub fn len(&self) -> usize {
1589 self.len
1590 }
1591
1592 pub fn is_empty(&self) -> bool {
1593 self.len == 0
1594 }
1595}
1596
1597impl Default for LogosDenseI64MapNoPresence {
1598 fn default() -> Self {
1599 Self::new()
1600 }
1601}
1602
1603#[derive(Debug, Clone)]
1609pub struct LogosDenseI64Set {
1610 present: Vec<u64>,
1611 lo: i64,
1612 len: usize,
1613}
1614
1615impl LogosDenseI64Set {
1616 pub fn new() -> Self {
1617 Self {
1618 present: Vec::new(),
1619 lo: 0,
1620 len: 0,
1621 }
1622 }
1623
1624 pub fn with_capacity(cap: usize) -> Self {
1625 Self::with_bounds(0, cap)
1626 }
1627
1628 pub fn with_bounds(lo: i64, slots: usize) -> Self {
1629 Self {
1630 present: vec![0; slots.div_ceil(64)],
1631 lo,
1632 len: 0,
1633 }
1634 }
1635
1636 #[inline]
1639 pub fn insert(&mut self, key: i64, _value: i64) {
1640 let idx = (key - self.lo) as usize;
1641 debug_assert!(
1642 key >= self.lo && idx < self.present.len() * 64,
1643 "dense set key {key} outside proven window starting at {}",
1644 self.lo
1645 );
1646 let bit = 1u64 << (idx & 63);
1647 let word = &mut self.present[idx >> 6];
1648 if *word & bit == 0 {
1649 *word |= bit;
1650 self.len += 1;
1651 }
1652 }
1653
1654 #[inline]
1655 pub fn contains_key(&self, key: &i64) -> bool {
1656 let idx = (*key - self.lo) as usize;
1657 debug_assert!(*key >= self.lo && idx < self.present.len() * 64);
1658 self.present[idx >> 6] & (1u64 << (idx & 63)) != 0
1659 }
1660
1661 pub fn len(&self) -> usize {
1662 self.len
1663 }
1664
1665 pub fn is_empty(&self) -> bool {
1666 self.len == 0
1667 }
1668}
1669
1670impl Default for LogosDenseI64Set {
1671 fn default() -> Self {
1672 Self::new()
1673 }
1674}
1675
1676impl LogosContains<i64> for LogosDenseI64Set {
1677 #[inline(always)]
1678 fn logos_contains(&self, key: &i64) -> bool {
1679 self.contains_key(key)
1680 }
1681}
1682
1683#[derive(Debug, Clone, Copy)]
1698pub struct LogosDivU64 {
1699 magic: u64,
1700 more: u8,
1703 d: u64,
1704}
1705
1706impl LogosDivU64 {
1707 const SHIFT_MASK: u8 = 0x3F;
1708 const ADD_MARKER: u8 = 0x40;
1709 const SHIFT_PATH: u8 = 0x80;
1710
1711 #[inline]
1715 pub fn new(d: u64) -> Self {
1716 debug_assert!(d != 0, "LogosDivU64: divisor must be non-zero");
1717 if d & (d - 1) == 0 {
1718 return Self {
1720 magic: 0,
1721 more: (d.trailing_zeros() as u8) | Self::SHIFT_PATH,
1722 d,
1723 };
1724 }
1725 let floor_log_2_d = 63 - d.leading_zeros();
1726 let numer = 1u128 << (64 + floor_log_2_d);
1728 let proposed_m = (numer / d as u128) as u64;
1729 let rem = (numer % d as u128) as u64;
1730 let e = d - rem;
1731 let (magic, more) = if e < (1u64 << floor_log_2_d) {
1732 (proposed_m + 1, floor_log_2_d as u8)
1734 } else {
1735 let twice_rem = rem.wrapping_mul(2);
1737 let bump = (twice_rem >= d || twice_rem < rem) as u64;
1738 (
1739 proposed_m.wrapping_mul(2).wrapping_add(bump) + 1,
1740 (floor_log_2_d as u8) | Self::ADD_MARKER,
1741 )
1742 };
1743 Self { magic, more, d }
1744 }
1745
1746 #[inline(always)]
1747 pub fn div(&self, numer: u64) -> u64 {
1748 if self.more & Self::SHIFT_PATH != 0 {
1749 return numer >> (self.more & Self::SHIFT_MASK);
1750 }
1751 let q = (((self.magic as u128) * (numer as u128)) >> 64) as u64;
1752 if self.more & Self::ADD_MARKER != 0 {
1753 let t = ((numer - q) >> 1).wrapping_add(q);
1754 t >> (self.more & Self::SHIFT_MASK)
1755 } else {
1756 q >> self.more
1757 }
1758 }
1759
1760 #[inline(always)]
1761 pub fn rem(&self, numer: u64) -> u64 {
1762 numer - self.div(numer).wrapping_mul(self.d)
1763 }
1764
1765 #[inline]
1771 pub fn parts(&self) -> (u64, u8) {
1772 (self.magic, self.more)
1773 }
1774}
1775
1776pub type Seq<T> = LogosSeq<T>;
1778
1779pub type Map<K, V> = LogosMap<K, V>;
1781
1782pub type FxIndexSet<T> = indexmap::IndexSet<T, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
1788pub type Set<T> = FxIndexSet<T>;
1789
1790pub trait LogosContains<T> {
1823 fn logos_contains(&self, value: &T) -> bool;
1825}
1826
1827impl<T: PartialEq> LogosContains<T> for Vec<T> {
1828 #[inline(always)]
1829 fn logos_contains(&self, value: &T) -> bool {
1830 self.contains(value)
1831 }
1832}
1833
1834impl<T: PartialEq> LogosContains<T> for [T] {
1835 #[inline(always)]
1836 fn logos_contains(&self, value: &T) -> bool {
1837 self.contains(value)
1838 }
1839}
1840
1841impl<T: Eq + Hash, S: std::hash::BuildHasher> LogosContains<T> for indexmap::IndexSet<T, S> {
1842 #[inline(always)]
1843 fn logos_contains(&self, value: &T) -> bool {
1844 self.contains(value)
1845 }
1846}
1847
1848impl<T: Eq + Hash> LogosContains<T> for rustc_hash::FxHashSet<T> {
1849 #[inline(always)]
1850 fn logos_contains(&self, value: &T) -> bool {
1851 self.contains(value)
1852 }
1853}
1854
1855impl<K: Eq + Hash, V> LogosContains<K> for rustc_hash::FxHashMap<K, V> {
1856 #[inline(always)]
1857 fn logos_contains(&self, key: &K) -> bool {
1858 self.contains_key(key)
1859 }
1860}
1861
1862impl LogosContains<&str> for String {
1863 #[inline(always)]
1864 fn logos_contains(&self, value: &&str) -> bool {
1865 self.contains(*value)
1866 }
1867}
1868
1869impl LogosContains<String> for String {
1870 #[inline(always)]
1871 fn logos_contains(&self, value: &String) -> bool {
1872 self.contains(value.as_str())
1873 }
1874}
1875
1876impl LogosContains<char> for String {
1877 #[inline(always)]
1878 fn logos_contains(&self, value: &char) -> bool {
1879 self.contains(*value)
1880 }
1881}
1882
1883impl<T: Eq + Hash + Clone, B: crate::crdt::SetBias> LogosContains<T> for crate::crdt::ORSet<T, B> {
1884 #[inline(always)]
1885 fn logos_contains(&self, value: &T) -> bool {
1886 self.contains(value)
1887 }
1888}
1889
1890#[derive(Clone, Debug, PartialEq)]
1931pub enum Value {
1932 Int(i64),
1934 Float(f64),
1936 Bool(bool),
1938 Text(String),
1940 Char(char),
1942 Seq(LogosSeq<Value>),
1947 Boxed(LogosBoxed),
1951 Nothing,
1953}
1954
1955impl std::fmt::Display for Value {
1956 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1957 match self {
1958 Value::Int(n) => write!(f, "{}", n),
1959 Value::Float(n) => write!(f, "{}", n),
1960 Value::Bool(b) => write!(f, "{}", b),
1961 Value::Text(s) => write!(f, "{}", s),
1962 Value::Char(c) => write!(f, "{}", c),
1963 Value::Seq(xs) => write!(f, "{}", xs),
1964 Value::Boxed(b) => write!(f, "{}", b),
1965 Value::Nothing => write!(f, "nothing"),
1966 }
1967 }
1968}
1969
1970pub trait Boxable: std::any::Any + Clone + PartialEq + std::fmt::Debug {
1974 fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
1975}
1976
1977trait BoxedValue: std::any::Any {
1979 fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
1980 fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
1981 fn equals(&self, other: &dyn BoxedValue) -> bool;
1982 fn as_any(&self) -> &dyn std::any::Any;
1983}
1984
1985impl<T: Boxable> BoxedValue for T {
1986 fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1987 Boxable::render(self, f)
1988 }
1989 fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1990 std::fmt::Debug::fmt(self, f)
1991 }
1992 fn equals(&self, other: &dyn BoxedValue) -> bool {
1993 other
1994 .as_any()
1995 .downcast_ref::<T>()
1996 .is_some_and(|other| self == other)
1997 }
1998 fn as_any(&self) -> &dyn std::any::Any {
1999 self
2000 }
2001}
2002
2003#[derive(Clone)]
2007pub struct LogosBoxed(Rc<dyn BoxedValue>);
2008
2009impl LogosBoxed {
2010 #[inline]
2011 pub fn new<T: Boxable>(value: T) -> Self {
2012 LogosBoxed(Rc::new(value))
2013 }
2014
2015 #[inline]
2018 pub fn get<T: Boxable>(&self) -> T {
2019 match self.0.as_any().downcast_ref::<T>() {
2020 Some(value) => value.clone(),
2021 None => panic!(
2022 "expected a {} tuple/record element, found {}",
2023 std::any::type_name::<T>(),
2024 self
2025 ),
2026 }
2027 }
2028}
2029
2030impl PartialEq for LogosBoxed {
2031 fn eq(&self, other: &Self) -> bool {
2032 self.0.equals(&*other.0)
2033 }
2034}
2035
2036impl std::fmt::Debug for LogosBoxed {
2037 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2038 self.0.debug(f)
2039 }
2040}
2041
2042impl std::fmt::Display for LogosBoxed {
2043 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2044 self.0.render(f)
2045 }
2046}
2047
2048impl<T: Boxable> From<T> for Value {
2049 #[inline]
2050 fn from(value: T) -> Self {
2051 Value::Boxed(LogosBoxed::new(value))
2052 }
2053}
2054
2055#[derive(Clone, Debug, PartialEq, Default)]
2061pub struct LogosTuple(pub Vec<Value>);
2062
2063impl std::ops::Deref for LogosTuple {
2064 type Target = Vec<Value>;
2065 fn deref(&self) -> &Vec<Value> {
2066 &self.0
2067 }
2068}
2069
2070impl std::ops::DerefMut for LogosTuple {
2071 fn deref_mut(&mut self) -> &mut Vec<Value> {
2072 &mut self.0
2073 }
2074}
2075
2076impl From<Vec<Value>> for LogosTuple {
2077 fn from(v: Vec<Value>) -> Self {
2078 LogosTuple(v)
2079 }
2080}
2081
2082impl std::fmt::Display for LogosTuple {
2083 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2084 write!(f, "(")?;
2085 for (i, v) in self.0.iter().enumerate() {
2086 if i > 0 {
2087 write!(f, ", ")?;
2088 }
2089 write!(f, "{}", v)?;
2090 }
2091 write!(f, ")")
2092 }
2093}
2094
2095impl From<i64> for Value {
2097 fn from(n: i64) -> Self {
2098 Value::Int(n)
2099 }
2100}
2101
2102impl From<f64> for Value {
2103 fn from(n: f64) -> Self {
2104 Value::Float(n)
2105 }
2106}
2107
2108impl From<bool> for Value {
2109 fn from(b: bool) -> Self {
2110 Value::Bool(b)
2111 }
2112}
2113
2114impl From<String> for Value {
2115 fn from(s: String) -> Self {
2116 Value::Text(s)
2117 }
2118}
2119
2120impl From<&str> for Value {
2121 fn from(s: &str) -> Self {
2122 Value::Text(s.to_string())
2123 }
2124}
2125
2126impl From<char> for Value {
2127 fn from(c: char) -> Self {
2128 Value::Char(c)
2129 }
2130}
2131
2132impl<T: Into<Value> + Clone> From<LogosSeq<T>> for Value {
2137 fn from(xs: LogosSeq<T>) -> Self {
2138 Value::Seq(LogosSeq::from_vec(
2139 xs.0.borrow().iter().cloned().map(Into::into).collect(),
2140 ))
2141 }
2142}
2143
2144pub type Tuple = Vec<Value>;
2146
2147impl Value {
2148 #[inline]
2155 pub fn logos_i64(self) -> i64 {
2156 match self {
2157 Value::Int(n) => n,
2158 other => panic!("expected an Int tuple/record element, found {other}"),
2159 }
2160 }
2161 #[inline]
2162 pub fn logos_f64(self) -> f64 {
2163 match self {
2164 Value::Float(x) => x,
2165 Value::Int(n) => n as f64,
2166 other => panic!("expected a Real tuple/record element, found {other}"),
2167 }
2168 }
2169 #[inline]
2170 pub fn logos_bool(self) -> bool {
2171 match self {
2172 Value::Bool(b) => b,
2173 other => panic!("expected a Bool tuple/record element, found {other}"),
2174 }
2175 }
2176 #[inline]
2177 pub fn logos_string(self) -> String {
2178 match self {
2179 Value::Text(s) => s,
2180 Value::Char(c) => c.to_string(),
2181 other => panic!("expected a Text tuple/record element, found {other}"),
2182 }
2183 }
2184 #[inline]
2185 pub fn logos_char(self) -> char {
2186 match self {
2187 Value::Char(c) => c,
2188 other => panic!("expected a Char tuple/record element, found {other}"),
2189 }
2190 }
2191 #[inline]
2193 pub fn logos_boxed<T: Boxable>(self) -> T {
2194 match self {
2195 Value::Boxed(b) => b.get(),
2196 other => panic!(
2197 "expected a {} tuple/record element, found {other}",
2198 std::any::type_name::<T>()
2199 ),
2200 }
2201 }
2202
2203 #[inline]
2208 pub fn logos_seq<T>(self, f: impl Fn(Value) -> T) -> LogosSeq<T> {
2209 match self {
2210 Value::Seq(xs) => LogosSeq::from_vec(xs.0.borrow().iter().cloned().map(f).collect()),
2211 other => panic!("expected a Seq tuple/record element, found {other}"),
2212 }
2213 }
2214 #[inline]
2215 pub fn logos_seq_i64(self) -> LogosSeq<i64> {
2216 self.logos_seq(Value::logos_i64)
2217 }
2218 #[inline]
2219 pub fn logos_seq_f64(self) -> LogosSeq<f64> {
2220 self.logos_seq(Value::logos_f64)
2221 }
2222 #[inline]
2223 pub fn logos_seq_bool(self) -> LogosSeq<bool> {
2224 self.logos_seq(Value::logos_bool)
2225 }
2226 #[inline]
2227 pub fn logos_seq_string(self) -> LogosSeq<String> {
2228 self.logos_seq(Value::logos_string)
2229 }
2230 #[inline]
2231 pub fn logos_seq_seq_i64(self) -> LogosSeq<LogosSeq<i64>> {
2232 self.logos_seq(Value::logos_seq_i64)
2233 }
2234 #[inline]
2235 pub fn logos_seq_seq_f64(self) -> LogosSeq<LogosSeq<f64>> {
2236 self.logos_seq(Value::logos_seq_f64)
2237 }
2238 #[inline]
2239 pub fn logos_seq_seq_bool(self) -> LogosSeq<LogosSeq<bool>> {
2240 self.logos_seq(Value::logos_seq_bool)
2241 }
2242 #[inline]
2243 pub fn logos_seq_seq_string(self) -> LogosSeq<LogosSeq<String>> {
2244 self.logos_seq(Value::logos_seq_string)
2245 }
2246}
2247
2248impl std::ops::Add for Value {
2253 type Output = Value;
2254
2255 #[inline]
2256 fn add(self, other: Value) -> Value {
2257 match (self, other) {
2258 (Value::Int(a), Value::Int(b)) => Value::Int(a + b),
2259 (Value::Float(a), Value::Float(b)) => Value::Float(a + b),
2260 (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 + b),
2261 (Value::Float(a), Value::Int(b)) => Value::Float(a + b as f64),
2262 (Value::Text(a), Value::Text(b)) => Value::Text(format!("{}{}", a, b)),
2263 _ => panic!("Cannot add these value types"),
2264 }
2265 }
2266}
2267
2268impl std::ops::Sub for Value {
2269 type Output = Value;
2270
2271 #[inline]
2272 fn sub(self, other: Value) -> Value {
2273 match (self, other) {
2274 (Value::Int(a), Value::Int(b)) => Value::Int(a - b),
2275 (Value::Float(a), Value::Float(b)) => Value::Float(a - b),
2276 (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 - b),
2277 (Value::Float(a), Value::Int(b)) => Value::Float(a - b as f64),
2278 _ => panic!("Cannot subtract these value types"),
2279 }
2280 }
2281}
2282
2283impl std::ops::Mul for Value {
2284 type Output = Value;
2285
2286 #[inline]
2287 fn mul(self, other: Value) -> Value {
2288 match (self, other) {
2289 (Value::Int(a), Value::Int(b)) => Value::Int(a * b),
2290 (Value::Float(a), Value::Float(b)) => Value::Float(a * b),
2291 (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 * b),
2292 (Value::Float(a), Value::Int(b)) => Value::Float(a * b as f64),
2293 _ => panic!("Cannot multiply these value types"),
2294 }
2295 }
2296}
2297
2298impl std::ops::Div for Value {
2299 type Output = Value;
2300
2301 #[inline]
2302 fn div(self, other: Value) -> Value {
2303 match (self, other) {
2304 (Value::Int(a), Value::Int(b)) => Value::Int(a / b),
2305 (Value::Float(a), Value::Float(b)) => Value::Float(a / b),
2306 (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 / b),
2307 (Value::Float(a), Value::Int(b)) => Value::Float(a / b as f64),
2308 _ => panic!("Cannot divide these value types"),
2309 }
2310 }
2311}
2312
2313#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
2322pub struct LogosRational(pub logicaffeine_base::Rational);
2323
2324impl LogosRational {
2325 #[inline]
2327 pub fn from_i64(n: i64) -> Self {
2328 LogosRational(logicaffeine_base::Rational::from_i64(n))
2329 }
2330
2331 #[inline]
2333 pub fn from_ratio(n: i64, d: i64) -> Self {
2334 LogosRational(
2335 logicaffeine_base::Rational::from_ratio_i64(n, d)
2336 .expect(crate::failure::DIVISION_BY_ZERO),
2337 )
2338 }
2339
2340 #[inline]
2341 pub fn add(&self, other: &LogosRational) -> LogosRational {
2342 LogosRational(self.0.add(&other.0))
2343 }
2344
2345 #[inline]
2346 pub fn sub(&self, other: &LogosRational) -> LogosRational {
2347 LogosRational(self.0.sub(&other.0))
2348 }
2349
2350 #[inline]
2351 pub fn mul(&self, other: &LogosRational) -> LogosRational {
2352 LogosRational(self.0.mul(&other.0))
2353 }
2354
2355 #[inline]
2357 pub fn div_exact(&self, other: &LogosRational) -> LogosRational {
2358 LogosRational(
2359 self.0
2360 .div(&other.0)
2361 .expect(crate::failure::DIVISION_BY_ZERO),
2362 )
2363 }
2364
2365 #[inline]
2367 pub fn abs(&self) -> LogosRational {
2368 LogosRational(self.0.abs())
2369 }
2370
2371 #[inline]
2374 pub fn floor(&self) -> i64 {
2375 self.0
2376 .floor()
2377 .to_i64()
2378 .expect("LOGOS runtime error: floor exceeds i64")
2379 }
2380
2381 #[inline]
2383 pub fn ceil(&self) -> i64 {
2384 self.0
2385 .ceil()
2386 .to_i64()
2387 .expect("LOGOS runtime error: ceiling exceeds i64")
2388 }
2389
2390 #[inline]
2392 pub fn round(&self) -> i64 {
2393 self.0
2394 .round()
2395 .to_i64()
2396 .expect("LOGOS runtime error: round exceeds i64")
2397 }
2398
2399 fn exact(&self) -> crate::LogosValue {
2402 crate::LogosValue::from_rational(self.0.clone())
2403 }
2404
2405 fn of_exact(v: crate::LogosValue) -> LogosRational {
2407 match v {
2408 crate::LogosValue::Int(n) => LogosRational::from_i64(n),
2409 crate::LogosValue::BigInt(b) => LogosRational(logicaffeine_base::Rational::from_bigint((*b).clone())),
2410 crate::LogosValue::Rational(r) => LogosRational((*r).clone()),
2411 other => unreachable!("an operator over exact numbers answered a {}", other.type_name()),
2412 }
2413 }
2414
2415 fn exact_op(
2416 &self,
2417 other: &LogosRational,
2418 op: fn(&crate::LogosValue, &crate::LogosValue) -> Result<crate::LogosValue, String>,
2419 ) -> LogosRational {
2420 LogosRational::of_exact(crate::failure::answered(op(&self.exact(), &other.exact())))
2421 }
2422
2423 fn integer_op(
2424 &self,
2425 other: &LogosRational,
2426 op: fn(&crate::LogosValue, &crate::LogosValue) -> Result<crate::LogosValue, String>,
2427 ) -> i64 {
2428 match crate::failure::answered(op(&self.exact(), &other.exact())) {
2429 crate::LogosValue::Int(n) => n,
2430 other => unreachable!("an integer operator answered a {}", other.type_name()),
2431 }
2432 }
2433
2434 pub fn quotient(&self, other: &LogosRational) -> LogosRational {
2436 self.exact_op(other, crate::LogosValue::div)
2437 }
2438
2439 pub fn remainder(&self, other: &LogosRational) -> LogosRational {
2441 self.exact_op(other, crate::LogosValue::rem)
2442 }
2443
2444 pub fn floor_quotient(&self, other: &LogosRational) -> LogosRational {
2446 self.exact_op(other, crate::LogosValue::floor_div)
2447 }
2448
2449 pub fn power(&self, other: &LogosRational) -> LogosRational {
2451 self.exact_op(other, crate::LogosValue::pow)
2452 }
2453
2454 pub fn bit_and(&self, other: &LogosRational) -> i64 {
2456 self.integer_op(other, crate::LogosValue::bit_and)
2457 }
2458
2459 pub fn bit_or(&self, other: &LogosRational) -> i64 {
2461 self.integer_op(other, crate::LogosValue::bit_or)
2462 }
2463
2464 pub fn bit_xor(&self, other: &LogosRational) -> i64 {
2466 self.integer_op(other, crate::LogosValue::bit_xor)
2467 }
2468
2469 pub fn shl(&self, other: &LogosRational) -> i64 {
2471 self.integer_op(other, crate::LogosValue::shl)
2472 }
2473
2474 pub fn shr(&self, other: &LogosRational) -> i64 {
2476 self.integer_op(other, crate::LogosValue::shr)
2477 }
2478
2479 #[inline]
2481 pub fn to_f64(&self) -> f64 {
2482 self.0.to_f64()
2483 }
2484
2485 #[inline]
2487 pub fn order_real(&self, other: f64) -> Option<std::cmp::Ordering> {
2488 logicaffeine_base::numeric::cmp_rational_f64_exact(&self.0, other)
2489 }
2490
2491 pub fn integer(&self, past_word: &str, fraction: &str) -> i64 {
2494 if !self.0.is_integer() {
2495 return crate::failure::answered(Err(fraction.to_string()));
2496 }
2497 match self.0.to_bigint().and_then(|b| b.to_i64()) {
2498 Some(n) => n,
2499 None => crate::failure::answered(Err(past_word.to_string())),
2500 }
2501 }
2502}
2503
2504impl std::fmt::Display for LogosRational {
2505 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2506 std::fmt::Display::fmt(&self.0, f)
2507 }
2508}
2509
2510impl From<i64> for LogosRational {
2511 #[inline]
2512 fn from(n: i64) -> Self {
2513 LogosRational::from_i64(n)
2514 }
2515}
2516
2517impl Default for LogosRational {
2521 fn default() -> Self {
2522 LogosRational::from_i64(0)
2523 }
2524}
2525
2526impl From<LogosInt> for LogosRational {
2527 #[inline]
2528 fn from(n: LogosInt) -> Self {
2529 match n {
2530 LogosInt::Small(n) => LogosRational::from_i64(n),
2531 LogosInt::Big(b) => LogosRational(logicaffeine_base::Rational::from_bigint(*b)),
2532 }
2533 }
2534}
2535
2536pub trait ToRationals {
2539 type Rationals;
2541 fn to_rationals(&self) -> Self::Rationals;
2542}
2543
2544impl ToRationals for i64 {
2545 type Rationals = LogosRational;
2546 #[inline]
2547 fn to_rationals(&self) -> LogosRational {
2548 LogosRational::from_i64(*self)
2549 }
2550}
2551
2552impl ToRationals for LogosRational {
2553 type Rationals = LogosRational;
2554 #[inline]
2555 fn to_rationals(&self) -> LogosRational {
2556 self.clone()
2557 }
2558}
2559
2560impl<T: ToRationals> ToRationals for [T] {
2561 type Rationals = LogosSeq<T::Rationals>;
2562 fn to_rationals(&self) -> LogosSeq<T::Rationals> {
2563 LogosSeq::from_vec(self.iter().map(ToRationals::to_rationals).collect())
2564 }
2565}
2566
2567impl<T: ToRationals> ToRationals for Vec<T> {
2568 type Rationals = LogosSeq<T::Rationals>;
2569 fn to_rationals(&self) -> LogosSeq<T::Rationals> {
2570 self.as_slice().to_rationals()
2571 }
2572}
2573
2574impl<T: ToRationals> ToRationals for LogosSeq<T> {
2575 type Rationals = LogosSeq<T::Rationals>;
2576 fn to_rationals(&self) -> LogosSeq<T::Rationals> {
2577 self.0.borrow().as_slice().to_rationals()
2578 }
2579}
2580
2581impl std::ops::Add for LogosRational {
2586 type Output = LogosRational;
2587 #[inline]
2588 fn add(self, other: LogosRational) -> LogosRational {
2589 LogosRational(self.0.add(&other.0))
2590 }
2591}
2592impl std::ops::Sub for LogosRational {
2593 type Output = LogosRational;
2594 #[inline]
2595 fn sub(self, other: LogosRational) -> LogosRational {
2596 LogosRational(self.0.sub(&other.0))
2597 }
2598}
2599impl std::ops::Mul for LogosRational {
2600 type Output = LogosRational;
2601 #[inline]
2602 fn mul(self, other: LogosRational) -> LogosRational {
2603 LogosRational(self.0.mul(&other.0))
2604 }
2605}
2606impl std::ops::Div for LogosRational {
2607 type Output = LogosRational;
2608 #[inline]
2609 fn div(self, other: LogosRational) -> LogosRational {
2610 LogosRational(
2611 self.0
2612 .div(&other.0)
2613 .expect(crate::failure::DIVISION_BY_ZERO),
2614 )
2615 }
2616}
2617
2618#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
2624pub struct LogosDecimal(pub logicaffeine_base::Decimal);
2625
2626pub trait DecimalArg {
2630 fn into_decimal(self) -> LogosDecimal;
2631}
2632
2633impl DecimalArg for &str {
2634 fn into_decimal(self) -> LogosDecimal {
2635 LogosDecimal::parse(self)
2636 }
2637}
2638
2639impl DecimalArg for String {
2640 fn into_decimal(self) -> LogosDecimal {
2641 LogosDecimal::parse(&self)
2642 }
2643}
2644
2645impl DecimalArg for &String {
2646 fn into_decimal(self) -> LogosDecimal {
2647 LogosDecimal::parse(self)
2648 }
2649}
2650
2651impl DecimalArg for i64 {
2652 fn into_decimal(self) -> LogosDecimal {
2653 LogosDecimal::from_i64(self)
2654 }
2655}
2656
2657impl DecimalArg for LogosInt {
2658 fn into_decimal(self) -> LogosDecimal {
2659 match self {
2660 LogosInt::Small(n) => LogosDecimal::from_i64(n),
2661 LogosInt::Big(b) => LogosDecimal::parse(&b.to_string()),
2662 }
2663 }
2664}
2665
2666impl DecimalArg for LogosDecimal {
2667 fn into_decimal(self) -> LogosDecimal {
2668 self
2669 }
2670}
2671
2672impl DecimalArg for &LogosDecimal {
2673 fn into_decimal(self) -> LogosDecimal {
2674 self.clone()
2675 }
2676}
2677
2678impl DecimalArg for f64 {
2679 fn into_decimal(self) -> LogosDecimal {
2680 panic!("{}", crate::failure::decimal_needs_text_or_int("Float"))
2681 }
2682}
2683
2684impl DecimalArg for bool {
2685 fn into_decimal(self) -> LogosDecimal {
2686 panic!("{}", crate::failure::decimal_needs_text_or_int("Bool"))
2687 }
2688}
2689
2690impl DecimalArg for char {
2691 fn into_decimal(self) -> LogosDecimal {
2692 panic!("{}", crate::failure::decimal_needs_text_or_int("Char"))
2693 }
2694}
2695
2696pub fn decimal_of(v: impl DecimalArg) -> LogosDecimal {
2698 v.into_decimal()
2699}
2700
2701impl LogosDecimal {
2702 #[inline]
2704 pub fn from_i64(n: i64) -> Self {
2705 LogosDecimal(logicaffeine_base::Decimal::from_i64(n))
2706 }
2707
2708 #[inline]
2712 pub fn parse(s: &str) -> Self {
2713 match logicaffeine_base::Decimal::parse(s) {
2714 Some(d) => LogosDecimal(d),
2715 None => panic!("{}", crate::failure::not_a_decimal(s)),
2716 }
2717 }
2718
2719 #[inline]
2720 pub fn add(&self, other: &LogosDecimal) -> LogosDecimal {
2721 LogosDecimal(self.0.add(&other.0))
2722 }
2723
2724 #[inline]
2725 pub fn sub(&self, other: &LogosDecimal) -> LogosDecimal {
2726 LogosDecimal(self.0.sub(&other.0))
2727 }
2728
2729 #[inline]
2730 pub fn mul(&self, other: &LogosDecimal) -> LogosDecimal {
2731 LogosDecimal(self.0.mul(&other.0))
2732 }
2733
2734 #[inline]
2736 pub fn to_rational(&self) -> LogosRational {
2737 LogosRational(self.0.to_rational())
2738 }
2739
2740 #[inline]
2743 pub fn div_exact(&self, other: &LogosDecimal) -> LogosRational {
2744 self.to_rational().div_exact(&other.to_rational())
2745 }
2746
2747 #[inline]
2749 pub fn abs(&self) -> LogosDecimal {
2750 LogosDecimal(self.0.abs())
2751 }
2752}
2753
2754impl std::fmt::Display for LogosDecimal {
2755 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2756 std::fmt::Display::fmt(&self.0, f)
2757 }
2758}
2759
2760impl From<i64> for LogosDecimal {
2761 #[inline]
2762 fn from(n: i64) -> Self {
2763 LogosDecimal::from_i64(n)
2764 }
2765}
2766
2767#[derive(Clone, Debug, PartialEq, Eq, Hash)]
2771pub struct LogosComplex(pub logicaffeine_base::Complex);
2772
2773impl LogosComplex {
2774 #[inline]
2776 pub fn from_i64(n: i64) -> Self {
2777 LogosComplex(logicaffeine_base::Complex::from_i64(n))
2778 }
2779
2780 #[inline]
2782 pub fn new(re: LogosRational, im: LogosRational) -> Self {
2783 LogosComplex(logicaffeine_base::Complex::new(re.0, im.0))
2784 }
2785
2786 #[inline]
2787 pub fn add(&self, other: &LogosComplex) -> LogosComplex {
2788 LogosComplex(self.0.add(&other.0))
2789 }
2790
2791 #[inline]
2792 pub fn sub(&self, other: &LogosComplex) -> LogosComplex {
2793 LogosComplex(self.0.sub(&other.0))
2794 }
2795
2796 #[inline]
2797 pub fn mul(&self, other: &LogosComplex) -> LogosComplex {
2798 LogosComplex(self.0.mul(&other.0))
2799 }
2800
2801 #[inline]
2803 pub fn div_exact(&self, other: &LogosComplex) -> LogosComplex {
2804 LogosComplex(
2805 self.0
2806 .div(&other.0)
2807 .expect(crate::failure::DIVISION_BY_ZERO),
2808 )
2809 }
2810
2811 #[inline]
2813 pub fn conjugate(&self) -> LogosComplex {
2814 LogosComplex(self.0.conjugate())
2815 }
2816 #[inline]
2818 pub fn re(&self) -> f64 {
2819 self.0.re().to_f64()
2820 }
2821 #[inline]
2823 pub fn im(&self) -> f64 {
2824 self.0.im().to_f64()
2825 }
2826 #[inline]
2829 pub fn abs_f64(&self) -> f64 {
2830 self.0.abs_f64()
2831 }
2832}
2833
2834impl std::fmt::Display for LogosComplex {
2835 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2836 std::fmt::Display::fmt(&self.0, f)
2837 }
2838}
2839
2840impl From<i64> for LogosComplex {
2841 #[inline]
2842 fn from(n: i64) -> Self {
2843 LogosComplex::from_i64(n)
2844 }
2845}
2846
2847#[derive(Clone, Copy, Debug, PartialEq)]
2852pub struct LogosComplexF(pub logicaffeine_base::ComplexF);
2853
2854impl LogosComplexF {
2855 #[inline]
2857 pub fn from_f64(re: f64) -> Self {
2858 LogosComplexF(logicaffeine_base::ComplexF::from_f64(re))
2859 }
2860 #[inline]
2862 pub fn new(re: f64, im: f64) -> Self {
2863 LogosComplexF(logicaffeine_base::ComplexF::new(re, im))
2864 }
2865 #[inline]
2866 pub fn add(&self, other: &LogosComplexF) -> LogosComplexF {
2867 LogosComplexF(self.0.add(&other.0))
2868 }
2869 #[inline]
2870 pub fn sub(&self, other: &LogosComplexF) -> LogosComplexF {
2871 LogosComplexF(self.0.sub(&other.0))
2872 }
2873 #[inline]
2874 pub fn mul(&self, other: &LogosComplexF) -> LogosComplexF {
2875 LogosComplexF(self.0.mul(&other.0))
2876 }
2877 #[inline]
2879 pub fn div_exact(&self, other: &LogosComplexF) -> LogosComplexF {
2880 LogosComplexF(
2881 self.0
2882 .div(&other.0)
2883 .expect(crate::failure::DIVISION_BY_ZERO),
2884 )
2885 }
2886 #[inline]
2888 pub fn sqrt(&self) -> LogosComplexF {
2889 LogosComplexF(self.0.sqrt())
2890 }
2891 #[inline]
2892 pub fn conjugate(&self) -> LogosComplexF {
2893 LogosComplexF(self.0.conjugate())
2894 }
2895 #[inline]
2896 pub fn abs(&self) -> f64 {
2897 self.0.abs()
2898 }
2899 #[inline]
2901 pub fn re(&self) -> f64 {
2902 self.0.re()
2903 }
2904 #[inline]
2906 pub fn im(&self) -> f64 {
2907 self.0.im()
2908 }
2909}
2910
2911impl std::fmt::Display for LogosComplexF {
2912 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2913 let (re, im) = (self.0.re(), self.0.im());
2915 let g = crate::fmt::fmt_f64;
2916 if im == 0.0 {
2917 return write!(f, "{}", g(re));
2918 }
2919 let mag = im.abs();
2920 let icoef = if mag == 1.0 { String::new() } else { g(mag) };
2921 if re == 0.0 {
2922 write!(f, "{}{}i", if im < 0.0 { "-" } else { "" }, icoef)
2923 } else {
2924 write!(f, "{}{}{}i", g(re), if im < 0.0 { "-" } else { "+" }, icoef)
2925 }
2926 }
2927}
2928
2929impl From<f64> for LogosComplexF {
2930 #[inline]
2931 fn from(re: f64) -> Self {
2932 LogosComplexF::from_f64(re)
2933 }
2934}
2935
2936#[derive(Clone, Debug, PartialEq, Eq, Hash)]
2940pub struct LogosModular(pub logicaffeine_base::Modular);
2941
2942impl LogosModular {
2943 #[inline]
2945 pub fn new(value: i64, modulus: i64) -> Self {
2946 LogosModular(
2947 logicaffeine_base::Modular::from_i64(value, modulus)
2948 .unwrap_or_else(|| panic!("{}", crate::failure::MODULUS_NOT_POSITIVE)),
2949 )
2950 }
2951
2952 #[inline]
2953 pub fn add(&self, other: &LogosModular) -> LogosModular {
2954 LogosModular(
2955 self.0
2956 .add(&other.0)
2957 .unwrap_or_else(|| panic!("{}", crate::failure::modular_rings_differ("add"))),
2958 )
2959 }
2960
2961 #[inline]
2962 pub fn sub(&self, other: &LogosModular) -> LogosModular {
2963 LogosModular(
2964 self.0
2965 .sub(&other.0)
2966 .unwrap_or_else(|| panic!("{}", crate::failure::modular_rings_differ("subtract"))),
2967 )
2968 }
2969
2970 #[inline]
2971 pub fn mul(&self, other: &LogosModular) -> LogosModular {
2972 LogosModular(
2973 self.0
2974 .mul(&other.0)
2975 .unwrap_or_else(|| panic!("{}", crate::failure::modular_rings_differ("multiply"))),
2976 )
2977 }
2978
2979 #[inline]
2982 pub fn div_exact(&self, other: &LogosModular) -> LogosModular {
2983 if self.0.modulus() != other.0.modulus() {
2984 panic!("{}", crate::failure::modular_rings_differ("divide"));
2985 }
2986 LogosModular(
2987 self.0
2988 .div(&other.0)
2989 .unwrap_or_else(|| panic!("{}", crate::failure::NO_MODULAR_INVERSE)),
2990 )
2991 }
2992
2993 #[inline]
2995 pub fn pow(&self, exp: u64) -> LogosModular {
2996 LogosModular(self.0.pow(exp))
2997 }
2998}
2999
3000impl std::fmt::Display for LogosModular {
3001 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3002 std::fmt::Display::fmt(&self.0, f)
3003 }
3004}
3005
3006#[derive(Clone, Debug)]
3013pub struct LogosQuantity {
3014 pub q: logicaffeine_base::Quantity,
3015 pub unit: logicaffeine_base::Unit,
3016}
3017
3018impl LogosQuantity {
3019 #[inline]
3021 pub fn of(value: i64, unit_name: &str) -> Self {
3022 Self::from_rational(LogosRational::from_i64(value), unit_name)
3023 }
3024
3025 pub fn from_rational(value: LogosRational, unit_name: &str) -> Self {
3028 let unit = logicaffeine_base::quantity::units::by_name(unit_name)
3029 .unwrap_or_else(|| panic!("{}", crate::failure::unknown_unit(unit_name)));
3030 LogosQuantity {
3031 q: logicaffeine_base::Quantity::of(value.0, &unit),
3032 unit,
3033 }
3034 }
3035
3036 #[inline]
3037 pub fn add(&self, other: &LogosQuantity) -> LogosQuantity {
3038 let q = self.q.add(&other.q).unwrap_or_else(|| {
3039 panic!(
3040 "{}",
3041 crate::failure::quantities_differ("add", self.q.dimension(), other.q.dimension())
3042 )
3043 });
3044 LogosQuantity {
3045 q,
3046 unit: self.unit.clone(),
3047 }
3048 }
3049
3050 #[inline]
3051 pub fn sub(&self, other: &LogosQuantity) -> LogosQuantity {
3052 let q = self.q.sub(&other.q).unwrap_or_else(|| {
3053 panic!(
3054 "{}",
3055 crate::failure::quantities_differ(
3056 "subtract",
3057 self.q.dimension(),
3058 other.q.dimension()
3059 )
3060 )
3061 });
3062 LogosQuantity {
3063 q,
3064 unit: self.unit.clone(),
3065 }
3066 }
3067
3068 #[inline]
3070 pub fn mul(&self, other: &LogosQuantity) -> LogosQuantity {
3071 let q = self.q.mul(&other.q);
3072 let unit = Self::si_unit(&q);
3073 LogosQuantity { q, unit }
3074 }
3075
3076 #[inline]
3077 pub fn div_exact(&self, other: &LogosQuantity) -> LogosQuantity {
3078 let q = self
3079 .q
3080 .div(&other.q)
3081 .unwrap_or_else(|| panic!("{}", crate::failure::DIVIDE_BY_ZERO_QUANTITY));
3082 let unit = Self::si_unit(&q);
3083 LogosQuantity { q, unit }
3084 }
3085
3086 #[inline]
3088 pub fn scale(&self, k: &LogosRational) -> LogosQuantity {
3089 let mag = self.q.magnitude_si().mul(&k.0);
3090 LogosQuantity {
3091 q: logicaffeine_base::Quantity::si(mag, self.q.dimension()),
3092 unit: self.unit.clone(),
3093 }
3094 }
3095
3096 #[inline]
3098 pub fn scale_int(&self, k: i64) -> LogosQuantity {
3099 self.scale(&LogosRational::from_i64(k))
3100 }
3101
3102 #[inline]
3104 pub fn div_int(&self, k: i64) -> LogosQuantity {
3105 self.div_scalar(&LogosRational::from_i64(k))
3106 }
3107
3108 #[inline]
3110 pub fn div_scalar(&self, k: &LogosRational) -> LogosQuantity {
3111 let mag = self
3112 .q
3113 .magnitude_si()
3114 .div(&k.0)
3115 .unwrap_or_else(|| panic!("{}", crate::failure::DIVIDE_QUANTITY_BY_ZERO));
3116 LogosQuantity {
3117 q: logicaffeine_base::Quantity::si(mag, self.q.dimension()),
3118 unit: self.unit.clone(),
3119 }
3120 }
3121
3122 pub fn convert(&self, unit_name: &str) -> LogosQuantity {
3125 let unit = logicaffeine_base::quantity::units::by_name(unit_name)
3126 .unwrap_or_else(|| panic!("{}", crate::failure::unknown_unit(unit_name)));
3127 if self.q.dimension() != unit.dimension {
3128 panic!(
3129 "{}",
3130 crate::failure::cannot_convert(&self.unit.symbol, &unit.symbol)
3131 );
3132 }
3133 LogosQuantity {
3134 q: self.q.clone(),
3135 unit,
3136 }
3137 }
3138
3139 fn si_unit(q: &logicaffeine_base::Quantity) -> logicaffeine_base::Unit {
3141 logicaffeine_base::Unit::linear("", q.dimension(), logicaffeine_base::Rational::one())
3142 }
3143}
3144
3145impl PartialEq for LogosQuantity {
3149 fn eq(&self, other: &Self) -> bool {
3150 self.q == other.q
3151 }
3152}
3153impl Eq for LogosQuantity {}
3154
3155impl PartialOrd for LogosQuantity {
3156 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
3157 if self.q.dimension() != other.q.dimension() {
3158 return None;
3159 }
3160 self.q.magnitude_si().partial_cmp(other.q.magnitude_si())
3161 }
3162}
3163
3164impl std::fmt::Display for LogosQuantity {
3165 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3166 let magnitude = self
3167 .q
3168 .in_unit(&self.unit)
3169 .expect("a Quantity's display unit always shares its dimension");
3170 if self.unit.symbol.is_empty() {
3171 write!(f, "{} {}", magnitude, self.q.dimension())
3172 } else {
3173 write!(f, "{} {}", magnitude, self.unit.symbol)
3174 }
3175 }
3176}
3177
3178#[derive(Clone, Debug)]
3182pub struct LogosMoney(pub logicaffeine_base::Money);
3183
3184impl Default for LogosDecimal {
3190 fn default() -> Self {
3191 LogosDecimal(logicaffeine_base::Decimal::zero())
3192 }
3193}
3194impl Default for LogosComplex {
3195 fn default() -> Self {
3196 LogosComplex(logicaffeine_base::Complex::zero())
3197 }
3198}
3199impl Default for LogosModular {
3200 fn default() -> Self {
3201 LogosModular(
3202 logicaffeine_base::Modular::from_i64(0, 1).expect("0 mod 1 is a valid modular value"),
3203 )
3204 }
3205}
3206impl Default for LogosUuid {
3207 fn default() -> Self {
3208 LogosUuid(logicaffeine_base::Uuid::NIL)
3209 }
3210}
3211impl Default for LogosMoney {
3212 fn default() -> Self {
3213 LogosMoney::from_i64(0, "USD")
3214 }
3215}
3216impl Default for LogosQuantity {
3217 fn default() -> Self {
3218 LogosQuantity {
3219 q: logicaffeine_base::Quantity::scalar(logicaffeine_base::Rational::zero()),
3220 unit: logicaffeine_base::Unit::linear(
3221 "",
3222 logicaffeine_base::Dimension::DIMENSIONLESS,
3223 logicaffeine_base::Rational::one(),
3224 ),
3225 }
3226 }
3227}
3228
3229impl LogosMoney {
3230 pub fn of(amount: LogosDecimal, code: &str) -> Self {
3233 let currency = logicaffeine_base::money::currency::by_code(code)
3234 .unwrap_or_else(|| panic!("{}", crate::failure::unknown_currency(code)));
3235 LogosMoney(logicaffeine_base::Money::of(amount.0, currency))
3236 }
3237
3238 pub fn from_i64(amount: i64, code: &str) -> Self {
3240 Self::of(
3241 LogosDecimal(logicaffeine_base::Decimal::from_i64(amount)),
3242 code,
3243 )
3244 }
3245
3246 #[inline]
3247 pub fn add(&self, other: &LogosMoney) -> LogosMoney {
3248 LogosMoney(self.0.add(&other.0).unwrap_or_else(|| {
3249 panic!(
3250 "{}",
3251 crate::failure::currencies_differ(
3252 "add",
3253 self.0.currency.code,
3254 other.0.currency.code
3255 )
3256 )
3257 }))
3258 }
3259
3260 #[inline]
3261 pub fn sub(&self, other: &LogosMoney) -> LogosMoney {
3262 LogosMoney(self.0.sub(&other.0).unwrap_or_else(|| {
3263 panic!(
3264 "{}",
3265 crate::failure::currencies_differ(
3266 "subtract",
3267 self.0.currency.code,
3268 other.0.currency.code
3269 )
3270 )
3271 }))
3272 }
3273
3274 #[inline]
3276 pub fn scale_int(&self, k: i64) -> LogosMoney {
3277 LogosMoney(self.0.scale_int(k))
3278 }
3279
3280 #[inline]
3282 pub fn scale_decimal(&self, k: &LogosDecimal) -> LogosMoney {
3283 LogosMoney(logicaffeine_base::Money::of(
3284 self.0.amount.mul(&k.0),
3285 self.0.currency,
3286 ))
3287 }
3288
3289 #[inline]
3291 pub fn div_int(&self, k: i64) -> LogosMoney {
3292 let d = self
3293 .0
3294 .amount
3295 .div(
3296 &logicaffeine_base::Decimal::from_i64(k),
3297 self.0.currency.scale,
3298 logicaffeine_base::RoundingMode::HalfEven,
3299 )
3300 .unwrap_or_else(|| panic!("{}", crate::failure::DIVIDE_MONEY_BY_ZERO));
3301 LogosMoney(logicaffeine_base::Money::of(d, self.0.currency))
3302 }
3303
3304 #[inline]
3306 pub fn ratio(&self, other: &LogosMoney) -> LogosRational {
3307 match self.0.ratio(&other.0) {
3308 Some(r) => LogosRational(r),
3309 None if self.0.currency != other.0.currency => panic!(
3310 "{}",
3311 crate::failure::currencies_differ(
3312 "compare",
3313 self.0.currency.code,
3314 other.0.currency.code
3315 )
3316 ),
3317 None => panic!("{}", crate::failure::DIVIDE_MONEY_BY_ZERO_AMOUNT),
3318 }
3319 }
3320}
3321
3322impl PartialEq for LogosMoney {
3323 fn eq(&self, other: &Self) -> bool {
3324 self.0 == other.0
3325 }
3326}
3327impl Eq for LogosMoney {}
3328
3329impl PartialOrd for LogosMoney {
3330 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
3332 if self.0.currency != other.0.currency {
3333 return None;
3334 }
3335 self.0
3336 .amount
3337 .to_rational()
3338 .partial_cmp(&other.0.amount.to_rational())
3339 }
3340}
3341
3342impl std::fmt::Display for LogosMoney {
3343 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3344 write!(f, "{}", self.0)
3345 }
3346}
3347
3348#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3351pub struct LogosUuid(pub logicaffeine_base::Uuid);
3352
3353impl LogosUuid {
3354 pub fn parse(s: &str) -> Self {
3357 LogosUuid(
3358 logicaffeine_base::Uuid::parse(s)
3359 .unwrap_or_else(|| panic!("{}", crate::failure::invalid_uuid(s))),
3360 )
3361 }
3362 pub fn nil() -> Self {
3364 LogosUuid(logicaffeine_base::Uuid::NIL)
3365 }
3366 pub fn max() -> Self {
3368 LogosUuid(logicaffeine_base::Uuid::MAX)
3369 }
3370 pub fn version(&self) -> i64 {
3372 self.0.version() as i64
3373 }
3374 pub fn namespace_dns() -> Self {
3376 LogosUuid(logicaffeine_base::Uuid::NAMESPACE_DNS)
3377 }
3378 pub fn namespace_url() -> Self {
3379 LogosUuid(logicaffeine_base::Uuid::NAMESPACE_URL)
3380 }
3381 pub fn namespace_oid() -> Self {
3382 LogosUuid(logicaffeine_base::Uuid::NAMESPACE_OID)
3383 }
3384 pub fn namespace_x500() -> Self {
3385 LogosUuid(logicaffeine_base::Uuid::NAMESPACE_X500)
3386 }
3387}
3388
3389impl LogosUuid {
3390 pub fn byte_seq(&self) -> LogosSeq<i64> {
3393 LogosSeq::from_vec(self.0.as_bytes().iter().map(|&b| b as i64).collect())
3394 }
3395 pub fn from_byte_seq(seq: &LogosSeq<i64>) -> LogosUuid {
3398 let v = seq.0.borrow();
3399 if v.len() < 16 {
3400 panic!("{}", crate::failure::uuid_needs_16_bytes(v.len()));
3401 }
3402 let mut b = [0u8; 16];
3403 for (i, slot) in b.iter_mut().enumerate() {
3404 *slot = (v[i] & 0xff) as u8;
3405 }
3406 LogosUuid(logicaffeine_base::Uuid::from_bytes(b))
3407 }
3408}
3409
3410pub fn text_bytes(s: &str) -> LogosSeq<i64> {
3412 LogosSeq::from_vec(s.as_bytes().iter().map(|&b| b as i64).collect())
3413}
3414
3415pub fn text_from_bytes(bytes: &LogosSeq<i64>) -> String {
3432 let b: Vec<u8> = bytes.iter().map(|v| v as u8).collect();
3433 match String::from_utf8(b) {
3434 Ok(s) => s,
3435 Err(e) => panic!("{}", crate::failure::invalid_utf8(e)),
3436 }
3437}
3438
3439impl std::fmt::Display for LogosUuid {
3440 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3441 write!(f, "{}", self.0)
3442 }
3443}
3444
3445pub trait IntoRate {
3449 fn into_rate(self) -> logicaffeine_base::Rational;
3450}
3451impl IntoRate for i64 {
3452 fn into_rate(self) -> logicaffeine_base::Rational {
3453 logicaffeine_base::Rational::from_i64(self)
3454 }
3455}
3456impl IntoRate for LogosDecimal {
3457 fn into_rate(self) -> logicaffeine_base::Rational {
3458 self.0.to_rational()
3459 }
3460}
3461impl IntoRate for LogosRational {
3462 fn into_rate(self) -> logicaffeine_base::Rational {
3463 self.0
3464 }
3465}
3466
3467pub fn set_rate<R: IntoRate>(code: String, rate: R) {
3471 logicaffeine_base::money::set_ambient_rate(&code, rate.into_rate());
3472}
3473
3474pub fn set_rates<V: IntoRate + Clone>(map: LogosMap<String, V>) {
3478 for (code, rate) in map.0.borrow().iter() {
3479 logicaffeine_base::money::set_ambient_rate(code, rate.clone().into_rate());
3480 }
3481}
3482
3483pub fn to_currency(money: LogosMoney, code: String) -> LogosMoney {
3487 let to = logicaffeine_base::money::currency::by_code(&code)
3488 .unwrap_or_else(|| panic!("{}", crate::failure::unknown_currency(&code)));
3489 let converted = logicaffeine_base::money::ambient_convert(&money.0, to).unwrap_or_else(|| {
3490 if logicaffeine_base::money::has_ambient_rates() {
3491 panic!(
3492 "{}",
3493 crate::failure::no_exchange_rate(money.0.currency.code, to.code)
3494 )
3495 } else {
3496 panic!("{}", crate::failure::NO_EXCHANGE_RATES)
3497 }
3498 });
3499 LogosMoney(converted)
3500}
3501
3502#[cfg(test)]
3503#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_money_tests.rs"]
3504mod logos_money_tests;
3505
3506#[cfg(test)]
3507#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_quantity_tests.rs"]
3508mod logos_quantity_tests;
3509
3510#[cfg(test)]
3511#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_rational_tests.rs"]
3512mod logos_rational_tests;
3513
3514#[cfg(test)]
3515#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/tests.rs"]
3516mod tests;
3517
3518#[cfg(test)]
3519#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_bits_tests.rs"]
3520mod logos_bits_tests;
3521
3522#[derive(Clone, Debug)]
3532pub enum LogosInt {
3533 Small(i64),
3534 Big(Box<logicaffeine_base::BigInt>),
3535}
3536
3537impl Default for LogosInt {
3540 fn default() -> Self {
3541 LogosInt::Small(0)
3542 }
3543}
3544
3545impl LogosInt {
3546 #[inline]
3547 pub fn from_i64(x: i64) -> Self {
3548 LogosInt::Small(x)
3549 }
3550
3551 pub fn from_big(b: logicaffeine_base::BigInt) -> Self {
3552 match b.to_i64() {
3553 Some(x) => LogosInt::Small(x),
3554 None => LogosInt::Big(Box::new(b)),
3555 }
3556 }
3557
3558 pub fn from_literal(s: &str) -> Self {
3560 if let Ok(x) = s.parse::<i64>() {
3561 return LogosInt::Small(x);
3562 }
3563 let (neg, digits) = match s.strip_prefix('-') {
3564 Some(d) => (true, d),
3565 None => (false, s),
3566 };
3567 let ten = logicaffeine_base::BigInt::from_i64(10);
3568 let mut acc = logicaffeine_base::BigInt::from_i64(0);
3569 for ch in digits.bytes() {
3570 debug_assert!(ch.is_ascii_digit(), "LogosInt literal digit");
3571 acc = acc
3572 .mul(&ten)
3573 .add(&logicaffeine_base::BigInt::from_i64((ch - b'0') as i64));
3574 }
3575 if neg {
3576 acc = acc.negated();
3577 }
3578 LogosInt::from_big(acc)
3579 }
3580
3581 fn to_bigint(&self) -> logicaffeine_base::BigInt {
3582 match self {
3583 LogosInt::Small(x) => logicaffeine_base::BigInt::from_i64(*x),
3584 LogosInt::Big(b) => (**b).clone(),
3585 }
3586 }
3587
3588 #[inline]
3594 fn as_bigint(&self) -> std::borrow::Cow<'_, logicaffeine_base::BigInt> {
3595 match self {
3596 LogosInt::Small(x) => std::borrow::Cow::Owned(logicaffeine_base::BigInt::from_i64(*x)),
3597 LogosInt::Big(b) => std::borrow::Cow::Borrowed(&**b),
3598 }
3599 }
3600
3601 pub fn to_i64(&self) -> Option<i64> {
3603 match self {
3604 LogosInt::Small(x) => Some(*x),
3605 LogosInt::Big(b) => b.to_i64(),
3606 }
3607 }
3608
3609 #[inline]
3611 pub fn wrapping_u64(&self) -> u64 {
3612 match self {
3613 Self::Small(value) => *value as u64,
3614 Self::Big(value) => value.wrapping_u64(),
3615 }
3616 }
3617
3618 #[inline]
3621 pub fn expect_i64(&self, what: &str) -> i64 {
3622 match self.to_i64() {
3623 Some(x) => x,
3624 None => panic!("Integer overflow: {self} does not fit a 64-bit {what}"),
3625 }
3626 }
3627
3628 #[inline]
3629 pub fn add(&self, rhs: &LogosInt) -> LogosInt {
3630 if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3631 if let Some(s) = a.checked_add(*b) {
3632 return LogosInt::Small(s);
3633 }
3634 }
3635 let (a, b) = (self.as_bigint(), rhs.as_bigint());
3636 LogosInt::from_big(a.add(&b))
3637 }
3638
3639 #[inline]
3640 pub fn sub(&self, rhs: &LogosInt) -> LogosInt {
3641 if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3642 if let Some(s) = a.checked_sub(*b) {
3643 return LogosInt::Small(s);
3644 }
3645 }
3646 let (a, b) = (self.as_bigint(), rhs.as_bigint());
3647 LogosInt::from_big(a.sub(&b))
3648 }
3649
3650 #[inline]
3651 pub fn mul(&self, rhs: &LogosInt) -> LogosInt {
3652 if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3653 if let Some(p) = a.checked_mul(*b) {
3654 return LogosInt::Small(p);
3655 }
3656 }
3657 let (a, b) = (self.as_bigint(), rhs.as_bigint());
3658 LogosInt::from_big(a.mul(&b))
3659 }
3660
3661 #[inline]
3668 pub fn mul_assign_i64(&mut self, rhs: i64) {
3669 match self {
3670 LogosInt::Small(a) => match a.checked_mul(rhs) {
3671 Some(p) => *a = p,
3672 None => {
3673 let big = logicaffeine_base::BigInt::from_i64(*a)
3674 .mul(&logicaffeine_base::BigInt::from_i64(rhs));
3675 *self = LogosInt::from_big(big);
3676 }
3677 },
3678 LogosInt::Big(b) => {
3679 if rhs == 0 {
3680 *self = LogosInt::Small(0);
3681 } else {
3682 b.mul_assign_i64(rhs);
3683 }
3684 }
3685 }
3686 }
3687
3688 #[inline]
3691 pub fn div(&self, rhs: &LogosInt) -> Result<LogosInt, String> {
3692 if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3693 if *b == 0 {
3694 return Err(crate::failure::DIVISION_BY_ZERO.to_string());
3695 }
3696 if let Some(q) = a.checked_div(*b) {
3697 return Ok(LogosInt::Small(q));
3698 }
3699 }
3700 match self.to_bigint().div_rem(&rhs.to_bigint()) {
3701 Some((q, _)) => Ok(LogosInt::from_big(q)),
3702 None => Err(crate::failure::DIVISION_BY_ZERO.to_string()),
3703 }
3704 }
3705
3706 pub fn div_floor(&self, rhs: &LogosInt) -> Result<LogosInt, String> {
3711 if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3712 if *b == 0 {
3713 return Err(crate::failure::DIVISION_BY_ZERO.to_string());
3714 }
3715 if let (Some(q), Some(r)) = (a.checked_div(*b), a.checked_rem(*b)) {
3719 let floored = if r != 0 && (r < 0) != (*b < 0) {
3720 q - 1
3721 } else {
3722 q
3723 };
3724 return Ok(LogosInt::Small(floored));
3725 }
3726 }
3727 match self.to_bigint().div_rem(&rhs.to_bigint()) {
3728 Some((q, r)) => {
3729 let floored = if !r.is_zero() && r.is_negative() != rhs.to_bigint().is_negative() {
3730 q.sub(&logicaffeine_base::BigInt::from_i64(1))
3731 } else {
3732 q
3733 };
3734 Ok(LogosInt::from_big(floored))
3735 }
3736 None => Err(crate::failure::DIVISION_BY_ZERO.to_string()),
3737 }
3738 }
3739
3740 #[inline]
3742 pub fn rem(&self, rhs: &LogosInt) -> Result<LogosInt, String> {
3743 if let (LogosInt::Small(a), LogosInt::Small(b)) = (self, rhs) {
3744 if *b == 0 {
3745 return Err(crate::failure::MODULO_BY_ZERO.to_string());
3746 }
3747 if let Some(r) = a.checked_rem(*b) {
3748 return Ok(LogosInt::Small(r));
3749 }
3750 return Ok(LogosInt::Small(0)); }
3752 match self.to_bigint().div_rem(&rhs.to_bigint()) {
3753 Some((_, r)) => Ok(LogosInt::from_big(r)),
3754 None => Err(crate::failure::MODULO_BY_ZERO.to_string()),
3755 }
3756 }
3757
3758 pub fn pow(&self, exp: &LogosInt) -> Result<LogosInt, String> {
3763 let e = match exp.to_i64() {
3764 Some(e) if e < 0 => {
3765 return Err("negative exponent on an integer (an Int can't hold a fraction — use a Float base)".to_string());
3766 }
3767 Some(e) => e,
3768 None => return Err("exponent too large".to_string()),
3769 };
3770 let e = u32::try_from(e).map_err(|_| "exponent too large".to_string())?;
3771 if let LogosInt::Small(b) = self {
3772 if let Some(r) = b.checked_pow(e) {
3773 return Ok(LogosInt::Small(r));
3774 }
3775 }
3776 Ok(LogosInt::from_big(self.to_bigint().pow(e)))
3777 }
3778
3779 pub fn neg(&self) -> LogosInt {
3780 match self {
3781 LogosInt::Small(x) => match x.checked_neg() {
3782 Some(n) => LogosInt::Small(n),
3783 None => LogosInt::from_big(self.to_bigint().negated()),
3784 },
3785 LogosInt::Big(b) => LogosInt::from_big(b.negated()),
3786 }
3787 }
3788}
3789
3790impl From<i64> for LogosInt {
3791 #[inline]
3792 fn from(x: i64) -> Self {
3793 LogosInt::Small(x)
3794 }
3795}
3796
3797impl PartialEq for LogosInt {
3798 fn eq(&self, other: &Self) -> bool {
3799 match (self, other) {
3800 (LogosInt::Small(a), LogosInt::Small(b)) => a == b,
3802 (LogosInt::Big(a), LogosInt::Big(b)) => **a == **b,
3803 _ => false,
3804 }
3805 }
3806}
3807impl Eq for LogosInt {}
3808
3809impl PartialEq<i64> for LogosInt {
3810 fn eq(&self, other: &i64) -> bool {
3811 matches!(self, LogosInt::Small(a) if a == other)
3812 }
3813}
3814impl PartialEq<LogosInt> for i64 {
3815 fn eq(&self, other: &LogosInt) -> bool {
3816 other == self
3817 }
3818}
3819
3820impl Ord for LogosInt {
3821 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
3822 match (self, other) {
3823 (LogosInt::Small(a), LogosInt::Small(b)) => a.cmp(b),
3824 _ => self.to_bigint().cmp(&other.to_bigint()),
3825 }
3826 }
3827}
3828impl PartialOrd for LogosInt {
3829 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
3830 Some(self.cmp(other))
3831 }
3832}
3833impl PartialOrd<i64> for LogosInt {
3834 fn partial_cmp(&self, other: &i64) -> Option<core::cmp::Ordering> {
3835 self.partial_cmp(&LogosInt::Small(*other))
3836 }
3837}
3838impl PartialOrd<LogosInt> for i64 {
3839 fn partial_cmp(&self, other: &LogosInt) -> Option<core::cmp::Ordering> {
3840 LogosInt::Small(*self).partial_cmp(other)
3841 }
3842}
3843
3844impl core::hash::Hash for LogosInt {
3845 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
3846 match self {
3848 LogosInt::Small(x) => logicaffeine_base::numeric::numeric_hash_i64(*x).hash(state),
3849 LogosInt::Big(b) => logicaffeine_base::numeric::numeric_hash_bigint(b).hash(state),
3850 }
3851 }
3852}
3853
3854impl core::fmt::Display for LogosInt {
3855 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3856 match self {
3857 LogosInt::Small(x) => write!(f, "{x}"),
3858 LogosInt::Big(b) => write!(f, "{b}"),
3859 }
3860 }
3861}
3862
3863#[cfg(test)]
3864#[path = "../../logicaffeine_tests/unit/logicaffeine_data/types/logos_int_spec.rs"]
3865mod logos_int_spec;