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
//! Janet tuple type.
use core::{
cmp::Ordering,
fmt::{self, Debug},
iter::FusedIterator,
marker::PhantomData,
ops::Index,
slice::{Chunks, ChunksExact, RChunks, RChunksExact, Windows},
};
use evil_janet::{janet_tuple_head, Janet as CJanet, JanetTupleHead};
use super::{Janet, JanetArray};
pub type Split<'a, P> = core::slice::Split<'a, Janet, P>;
pub type RSplit<'a, P> = core::slice::RSplit<'a, Janet, P>;
pub type SplitN<'a, P> = core::slice::SplitN<'a, Janet, P>;
pub type RSplitN<'a, P> = core::slice::RSplitN<'a, Janet, P>;
/// Builder for [`JanetTuple`]s.
#[derive(Debug)]
#[must_use = "builder cannot be utilized as a proper JanetTuple, use the `finish` method"]
pub struct JanetTupleBuilder<'data> {
raw: *mut CJanet,
len: i32,
added: i32,
phantom: PhantomData<&'data ()>,
}
impl<'data> JanetTupleBuilder<'data> {
/// Add a new value to the values in the tuple builder.
#[cfg_attr(feature = "inline-more", inline)]
pub fn put(mut self, value: impl Into<Janet>) -> Self {
let value = value.into();
if self.added >= self.len {
return self;
}
// SAFETY: We assured that if cannot try to write above it's max len in the lines above.
unsafe {
let val_ptr = self.raw.offset(self.added as isize);
*val_ptr = value.inner;
}
self.added += 1;
self
}
/// Finalie the build process and create [`JanetTuple`].
///
/// If the build is finalized and not all the allocated space was inserted with a
/// item, the unnused space will all have value of Janet number zero.
#[inline]
#[must_use = "function finishies building process and returns JanetStruct"]
pub fn finalize(self) -> JanetTuple<'data> {
JanetTuple {
raw: unsafe { evil_janet::janet_tuple_end(self.raw) },
phantom: PhantomData,
}
}
}
/// Janet [tuples](https://janet-lang.org/docs/data_structures/tuples.html) are immutable,
/// sequential types that are similar to [Janet arrays].
///
/// To facilitate the creation of this structure, you can use the macro
/// [`tuple`](crate::tuple!).
///
/// # Example
/// ```
/// use janetrs::{Janet, JanetTuple};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let tuple = JanetTuple::builder(2)
/// .put(Janet::number(10.0))
/// .put(Janet::boolean(true));
/// ```
///
/// [Janet arrays]: JanetArray
#[repr(transparent)]
pub struct JanetTuple<'data> {
pub(crate) raw: *const CJanet,
phantom: PhantomData<&'data ()>,
}
impl<'data> JanetTuple<'data> {
/// Start the build process to create a [`JanetTuple`].
///
/// If the given `len` is lesser than zero it behaves the same as if `len` is zero.
#[inline]
pub fn builder(len: i32) -> JanetTupleBuilder<'data> {
let len = if len < 0 { 0 } else { len };
JanetTupleBuilder {
raw: unsafe { evil_janet::janet_tuple_begin(len) },
len,
added: 0,
phantom: PhantomData,
}
}
/// Creates a tuple where all of it's elements are `elem`.
#[inline]
#[must_use = "function is a constructor associated function"]
pub fn with_default_elem(elem: Janet, len: i32) -> Self {
let len = if len < 0 { 0 } else { len };
let mut tuple = Self::builder(len);
for _ in 0..len {
tuple = tuple.put(elem);
}
tuple.finalize()
}
/// Create a new [`JanetTuple`] with a `raw` pointer.
///
/// # Safety
/// This function do not check if the given `raw` is `NULL` or not. Use at your
/// own risk.
#[inline]
#[must_use = "function is a constructor associated function"]
pub const unsafe fn from_raw(raw: *const CJanet) -> Self {
Self {
raw,
phantom: PhantomData,
}
}
// Get the [`JanetTupleHead`] from the `JanetStruct` pointer.
fn head(&self) -> &JanetTupleHead {
// SAFETY: Janet tuple are always a valid pointer
unsafe { &*janet_tuple_head(self.raw) }
}
// Get the [`JanetTupleHead`] from the `JanetStruct` pointer.
fn head_mut(&mut self) -> &mut JanetTupleHead {
// SAFETY: Janet tuple are always a valid pointer
unsafe { &mut *janet_tuple_head(self.raw) }
}
/// Returns the sourcemap metadata attached to `JanetTuple`, which is a Rust tuple
/// (line, column).
#[crate::cjvg("1.9.0")]
pub fn sourcemap(&self) -> (i32, i32) {
let head = self.head();
(head.sm_line, head.sm_column)
}
/// Set the sourcemap metadata on the `JanetTuple`.
#[crate::cjvg("1.9.0")]
pub fn set_sourcemap(&mut self, line: i32, column: i32) {
let head = self.head_mut();
head.sm_line = line;
head.sm_column = column;
}
/// Returns a reference to an element in the tuple.
///
/// # Examples
/// ```
/// use janetrs::{Janet, JanetTuple};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let tup = JanetTuple::builder(2).put("hey").put(11).finalize();
/// assert_eq!(tup.get(0), Some(&Janet::from("hey")));
/// assert_eq!(tup.get(1), Some(&Janet::integer(11)));
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn get(&self, index: i32) -> Option<&Janet> {
if index < 0 || index >= self.len() {
None
} else {
// SAFETY: it's safe because we just checked that it is in bounds
unsafe {
let item = self.raw.offset(index as isize) as *const Janet;
Some(&*item)
}
}
}
/// Returns a reference to an element, without doing bounds checking.
///
/// # Safety
/// Calling this method with an out-of-bounds index is *[undefined behavior]*
/// even if the resulting reference is not used.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub unsafe fn get_unchecked(&self, index: i32) -> &Janet {
let item = self.raw.offset(index as isize) as *const Janet;
&*item
}
/// Returns the number of elements in the tuple, also referred to as its 'length'.
///
/// # Examples
/// ```
/// use janetrs::JanetTuple;
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let tup = JanetTuple::builder(2).put("hey").put(11).finalize();
/// assert_eq!(tup.len(), 2);
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn len(&self) -> i32 {
self.head().length
}
/// Returns `true` if the tuple contains no elements.
///
/// # Examples
/// ```
/// use janetrs::JanetTuple;
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let tup = JanetTuple::builder(2).put("hey").put(11).finalize();
/// assert!(!tup.is_empty());
///
/// let tup = JanetTuple::builder(0).finalize();
/// assert!(tup.is_empty());
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns `true` if the tuple contains an element with the given `value`.
///
/// # Examples
/// ```
/// use janetrs::tuple;
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let tup = tuple![1.0, "foo", 4.0];
/// assert!(tup.contains("foo"));
/// ```
#[cfg_attr(feature = "inline-more", inline)]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn contains(&self, value: impl Into<Janet>) -> bool {
let value = value.into();
self.iter().any(|&elem| elem == value)
}
/// Returns a reference to the first element of the tuple, or `None` if it is empty.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![10, 40, 30];
/// assert_eq!(Some(&Janet::from(10)), v.first());
///
/// let w = tuple![];
/// assert_eq!(None, w.first());
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn first(&self) -> Option<&Janet> {
if let [first, ..] = self.as_ref() {
Some(first)
} else {
None
}
}
/// Returns a reference of the first and a reference to all the rest of the elements
/// of the tuple, or `None` if it is empty.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let x = tuple![0, 1, 2];
///
/// if let Some((first, elements)) = x.split_first() {
/// assert_eq!(first, &Janet::from(0));
/// assert_eq!(elements, &[Janet::from(1), Janet::from(2)]);
/// }
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn split_first(&self) -> Option<(&Janet, &[Janet])> {
if let [first, tail @ ..] = self.as_ref() {
Some((first, tail))
} else {
None
}
}
/// Returns a reference to the last element of the tuple, or `None` if it is empty.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![10, 40, 30];
/// assert_eq!(Some(&Janet::from(30)), v.last());
///
/// let w = tuple![];
/// assert_eq!(None, w.last());
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn last(&self) -> Option<&Janet> {
if let [.., last] = self.as_ref() {
Some(last)
} else {
None
}
}
/// Returns a reference of the last and all the rest of the elements of the array, or
/// `None` if it is empty.
///
/// # Examples
///
/// ```
/// use janetrs::{array, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let x = array![0, 1, 2];
///
/// if let Some((last, elements)) = x.split_last() {
/// assert_eq!(last, &Janet::from(2));
/// assert_eq!(elements, &[Janet::from(0), Janet::from(1)]);
/// }
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn split_last(&self) -> Option<(&Janet, &[Janet])> {
if let [init @ .., last] = self.as_ref() {
Some((last, init))
} else {
None
}
}
/// Divides one tuple into two at an index.
///
/// The first will contain all indices from `[0, mid)` (excluding
/// the index `mid` itself) and the second will contain all
/// indices from `[mid, len)` (excluding the index `len` itself).
///
/// # Panics
///
/// Panics if `mid > len` or `mid < 0`.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![1, 2, 3, 4, 5, 6];
///
/// {
/// let (left, right) = v.split_at(0);
/// assert!(left.is_empty());
/// assert_eq!(right, tuple![1, 2, 3, 4, 5, 6].as_ref());
/// }
///
/// {
/// let (left, right) = v.split_at(2);
/// assert_eq!(left, tuple![1, 2].as_ref());
/// assert_eq!(right, tuple![3, 4, 5, 6].as_ref());
/// }
///
/// {
/// let (left, right) = v.split_at(6);
/// assert_eq!(left, tuple![1, 2, 3, 4, 5, 6].as_ref());
/// assert!(right.is_empty());
/// }
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn split_at(&self, mid: i32) -> (&[Janet], &[Janet]) {
if mid < 0 {
crate::jpanic!(
"index out of bounds: the index ({}) is negative and must be positive",
mid
)
}
self.as_ref().split_at(mid as usize)
}
/// Creates a tuple by repeating a tuple `n` times.
///
/// # Panics
///
/// This function will panic if the capacity would overflow.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// assert_eq!(
/// tuple![1, 2].repeat(3).as_ref(),
/// tuple![1, 2, 1, 2, 1, 2].as_ref()
/// );
/// ```
///
/// A panic upon overflow:
///
/// ```should_panic
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// // this will panic at runtime
/// b"0123456789abcdef".repeat(usize::MAX);
/// ```
#[inline]
#[must_use = "this returns a new JanetArray, without modifying the original"]
pub fn repeat(&self, n: usize) -> JanetArray {
self.as_ref().repeat(n).into_iter().collect()
}
/// Returns `true` if `needle` is a prefix of the tuple.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![10, 40, 30];
/// assert!(v.starts_with(&[Janet::from(10)]));
/// assert!(v.starts_with(&[Janet::from(10), Janet::from(40)]));
/// assert!(!v.starts_with(&[Janet::from(50)]));
/// assert!(!v.starts_with(&[Janet::from(10), Janet::from(50)]));
/// ```
///
/// Always returns `true` if `needle` is an empty slice:
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![10, 40, 30];
/// assert!(v.starts_with(&[]));
/// let v = tuple![];
/// assert!(v.starts_with(&[]));
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn starts_with(&self, needle: &[Janet]) -> bool {
self.as_ref().starts_with(needle)
}
/// Returns `true` if `needle` is a suffix of the tuple.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![10, 40, 30];
/// assert!(v.ends_with(&[Janet::from(30)]));
/// assert!(v.ends_with(&[Janet::from(40), Janet::from(30)]));
/// assert!(!v.ends_with(&[Janet::from(50)]));
/// assert!(!v.ends_with(&[Janet::from(50), Janet::from(30)]));
/// ```
///
/// Always returns `true` if `needle` is an empty slice:
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![10, 40, 30];
/// assert!(v.ends_with(&[]));
/// let v = tuple![];
/// assert!(v.ends_with(&[]));
/// ```
#[inline]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn ends_with(&self, needle: &[Janet]) -> bool {
self.as_ref().ends_with(needle)
}
/// Binary searches this tuple for a given element.
///
/// If the value is found then [`Result::Ok`] is returned, containing the
/// index of the matching element. If there are multiple matches, then any
/// one of the matches could be returned. If the value is not found then
/// [`Result::Err`] is returned, containing the index where a matching
/// element could be inserted while maintaining sorted order.
///
/// # Examples
///
/// Looks up a series of four elements. The first is found, with a
/// uniquely determined position; the second and third are not
/// found; the fourth could match any position in `[1, 4]`.
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let s = tuple![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
///
/// assert_eq!(s.binary_search(&Janet::from(13)), Ok(9));
/// assert_eq!(s.binary_search(&Janet::from(4)), Err(7));
/// assert_eq!(s.binary_search(&Janet::from(100)), Err(13));
/// let r = s.binary_search(&Janet::from(1));
/// assert!(match r {
/// Ok(1..=4) => true,
/// _ => false,
/// });
/// ```
///
/// If you want to insert an item to a sorted vector, while maintaining
/// sort order:
///
/// ```
/// use janetrs::{tuple, Janet, JanetArray};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let mut s = tuple![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
/// let num = Janet::from(42);
/// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
/// let mut s = JanetArray::from(s);
/// s.insert(idx as i32, num);
/// assert_eq!(
/// s.as_ref(),
/// tuple![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55].as_ref()
/// );
/// ```
#[inline]
pub fn binary_search(&self, x: &Janet) -> Result<usize, usize> {
self.binary_search_by(|p| p.cmp(x))
}
/// Binary searches this sorted tuple with a comparator function.
///
/// The comparator function should implement an order consistent
/// with the sort order of the underlying slice, returning an
/// order code that indicates whether its argument is `Less`,
/// `Equal` or `Greater` the desired target.
///
/// If the value is found then [`Result::Ok`] is returned, containing the
/// index of the matching element. If there are multiple matches, then any
/// one of the matches could be returned. If the value is not found then
/// [`Result::Err`] is returned, containing the index where a matching
/// element could be inserted while maintaining sorted order.
///
/// # Examples
///
/// Looks up a series of four elements. The first is found, with a
/// uniquely determined position; the second and third are not
/// found; the fourth could match any position in `[1, 4]`.
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let s = tuple![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
///
/// let seek = Janet::from(13);
/// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
/// let seek = Janet::from(4);
/// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
/// let seek = Janet::from(100);
/// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
/// let seek = Janet::from(1);
/// let r = s.binary_search_by(|probe| probe.cmp(&seek));
/// assert!(match r {
/// Ok(1..=4) => true,
/// _ => false,
/// });
/// ```
#[inline]
pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
where
F: FnMut(&'a Janet) -> Ordering,
{
self.as_ref().binary_search_by(f)
}
/// Binary searches this tuple with a key extraction function.
///
/// Assumes that the tuple is sorted by the key, for instance with
/// [`sort_by_key`] using the same key extraction function.
///
/// If the value is found then [`Result::Ok`] is returned, containing the
/// index of the matching element. If there are multiple matches, then any
/// one of the matches could be returned. If the value is not found then
/// [`Result::Err`] is returned, containing the index where a matching
/// element could be inserted while maintaining sorted order.
///
/// [`sort_by_key`]: #method.sort_by_key
///
/// # Examples
/// TODO: Find a good example
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
/// ```
#[inline]
pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
where
F: FnMut(&'a Janet) -> B,
B: Ord,
{
self.binary_search_by(|k| f(k).cmp(b))
}
/// Creates a iterator over the reference of the array items.
#[inline]
pub fn iter(&self) -> Iter<'_, '_> {
Iter {
tup: self,
index_head: 0,
index_tail: self.len(),
}
}
/// Creates an iterator over all contiguous windows of length
/// `size`. The windows overlap. If the tuple is shorter than
/// `size`, the iterator returns no values.
///
/// # Panics
///
/// Panics if `size` is 0.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple!['r', 'u', 's', 't'];
/// let mut iter = arr.windows(2);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('r'), Janet::from('u')]);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('u'), Janet::from('s')]);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('s'), Janet::from('t')]);
/// assert!(iter.next().is_none());
/// ```
///
/// If the tuple is shorter than `size`:
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple!['f', 'o', 'o'];
/// let mut iter = arr.windows(4);
/// assert!(iter.next().is_none());
/// ```
#[inline]
pub fn windows(&self, size: usize) -> Windows<'_, Janet> {
self.as_ref().windows(size)
}
/// Creates an iterator over `chunk_size` elements of the tuple at a time, starting at
/// the beginning of the tuple.
///
/// The chunks are slices and do not overlap. If `chunk_size` does not divide the
/// length of the tuple, then the last chunk will not have length `chunk_size`.
///
/// See [`chunks_exact`] for a variant of this iterator that returns chunks of always
/// exactly `chunk_size` elements, and [`rchunks`] for the same iterator but
/// starting at the end of the tuple.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple!['l', 'o', 'r', 'e', 'm'];
/// let mut iter = arr.chunks(2);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('l'), Janet::from('o')]);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('r'), Janet::from('e')]);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('m')]);
/// assert!(iter.next().is_none());
/// ```
///
/// [`chunks_exact`]: #method.chunks_exact
/// [`rchunks`]: #method.rchunks
#[inline]
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, Janet> {
self.as_ref().chunks(chunk_size)
}
/// Creates an iterator over `chunk_size` elements of the tuple at a time, starting at
/// the beginning of the tuple.
///
/// The chunks are slices and do not overlap. If `chunk_size` does not divide the
/// length of the tuple, then the last up to `chunk_size-1` elements will be
/// omitted and can be retrieved from the `remainder` function of the iterator.
///
/// Due to each chunk having exactly `chunk_size` elements, the compiler can often
/// optimize the resulting code better than in the case of [`chunks`].
///
/// See [`chunks`] for a variant of this iterator that also returns the remainder as a
/// smaller chunk, and [`rchunks_exact`] for the same iterator but starting at the
/// end of the tuple.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple!['l', 'o', 'r', 'e', 'm'];
/// let mut iter = arr.chunks_exact(2);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('l'), Janet::from('o')]);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('r'), Janet::from('e')]);
/// assert!(iter.next().is_none());
/// assert_eq!(iter.remainder(), &[Janet::from('m')]);
/// ```
///
/// [`chunks`]: #method.chunks
/// [`rchunks_exact`]: #method.rchunks_exact
#[inline]
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, Janet> {
self.as_ref().chunks_exact(chunk_size)
}
/// Create an iterator over `chunk_size` elements of the tuple at a time, starting at
/// the end of the tuple.
///
/// The chunks are slices and do not overlap. If `chunk_size` does not divide the
/// length of the tuple, then the last chunk will not have length `chunk_size`.
///
/// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always
/// exactly `chunk_size` elements, and [`chunks`] for the same iterator but
/// starting at the beginning of the tuple.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple!['l', 'o', 'r', 'e', 'm'];
/// let mut iter = arr.rchunks(2);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('e'), Janet::from('m')]);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('o'), Janet::from('r')]);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('l')]);
/// assert!(iter.next().is_none());
/// ```
///
/// [`rchunks_exact`]: #method.rchunks_exact
/// [`chunks`]: #method.chunks
#[inline]
pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, Janet> {
self.as_ref().rchunks(chunk_size)
}
/// Returns an iterator over `chunk_size` elements of the tuple at a time, starting at
/// the end of the tuple.
///
/// The chunks are slices and do not overlap. If `chunk_size` does not divide the
/// length of the tuple, then the last up to `chunk_size-1` elements will be
/// omitted and can be retrieved from the `remainder` function of the iterator.
///
/// Due to each chunk having exactly `chunk_size` elements, the compiler can often
/// optimize the resulting code better than in the case of [`chunks`].
///
/// See [`rchunks`] for a variant of this iterator that also returns the remainder as
/// a smaller chunk, and [`chunks_exact`] for the same iterator but starting at
/// the beginning of the tuple.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple!['l', 'o', 'r', 'e', 'm'];
/// let mut iter = arr.rchunks_exact(2);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('e'), Janet::from('m')]);
/// assert_eq!(iter.next().unwrap(), &[Janet::from('o'), Janet::from('r')]);
/// assert!(iter.next().is_none());
/// assert_eq!(iter.remainder(), &[Janet::from('l')]);
/// ```
///
/// [`chunks`]: #method.chunks
/// [`rchunks`]: #method.rchunks
/// [`chunks_exact`]: #method.chunks_exact
#[inline]
pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, Janet> {
self.as_ref().rchunks_exact(chunk_size)
}
/// Creates an iterator over subslices separated by elements that match
/// `pred`. The matched element is not contained in the subslices.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet, TaggedJanet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple![10, 40, 33, 20];
/// let mut iter = arr.split(|j| match j.unwrap() {
/// TaggedJanet::Number(num) => (num % 3.0) as u128 == 0,
/// _ => false,
/// });
///
/// assert_eq!(iter.next().unwrap(), tuple![10, 40].as_ref());
/// assert_eq!(iter.next().unwrap(), tuple![20].as_ref());
/// assert!(iter.next().is_none());
/// ```
///
/// If the first element is matched, an empty slice will be the first item
/// returned by the iterator. Similarly, if the last element in the slice
/// is matched, an empty slice will be the last item returned by the
/// iterator:
///
/// ```
/// use janetrs::{tuple, Janet, TaggedJanet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple![10, 40, 33];
/// let mut iter = arr.split(|j| match j.unwrap() {
/// TaggedJanet::Number(num) => (num % 3.0) as u128 == 0,
/// _ => false,
/// });
///
/// assert_eq!(iter.next().unwrap(), tuple![10, 40].as_ref());
/// assert_eq!(iter.next().unwrap(), tuple![].as_ref());
/// assert!(iter.next().is_none());
/// ```
///
/// If two matched elements are directly adjacent, an empty slice will be
/// present between them:
///
/// ```
/// use janetrs::{tuple, Janet, TaggedJanet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple![10, 6, 33, 20];
/// let mut iter = arr.split(|j| match j.unwrap() {
/// TaggedJanet::Number(num) => (num % 3.0) as u128 == 0,
/// _ => false,
/// });
///
/// assert_eq!(iter.next().unwrap(), tuple![10].as_ref());
/// assert_eq!(iter.next().unwrap(), tuple![].as_ref());
/// assert_eq!(iter.next().unwrap(), tuple![20].as_ref());
/// assert!(iter.next().is_none());
/// ```
#[inline]
pub fn split<F>(&self, pred: F) -> Split<'_, F>
where
F: FnMut(&Janet) -> bool,
{
self.as_ref().split(pred)
}
/// Creates an iterator over subslices separated by elements that match
/// `pred`, starting at the end of the slice and working backwards.
/// The matched element is not contained in the subslices.
///
/// # Examples
///
/// ```
/// use janetrs::{tuple, Janet, TaggedJanet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let arr = tuple![11, 22, 33, 0, 44, 55];
/// let mut iter = arr.rsplit(|j| match j.unwrap() {
/// TaggedJanet::Number(num) => num as i64 == 0,
/// _ => false,
/// });
///
/// assert_eq!(iter.next().unwrap(), tuple![44, 55].as_ref());
/// assert_eq!(iter.next().unwrap(), tuple![11, 22, 33].as_ref());
/// assert_eq!(iter.next(), None);
/// ```
///
/// As with `split()`, if the first or last element is matched, an empty
/// slice will be the first (or last) item returned by the iterator.
///
/// ```
/// use janetrs::{tuple, Janet, TaggedJanet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![0, 1, 1, 2, 3, 5, 8];
/// let mut it = v.rsplit(|j| match j.unwrap() {
/// TaggedJanet::Number(n) => n as i64 % 2 == 0,
/// _ => false,
/// });
/// assert_eq!(it.next().unwrap(), tuple![].as_ref());
/// assert_eq!(it.next().unwrap(), tuple![3, 5].as_ref());
/// assert_eq!(it.next().unwrap(), tuple![1, 1].as_ref());
/// assert_eq!(it.next().unwrap(), tuple![].as_ref());
/// assert_eq!(it.next(), None);
/// ```
#[inline]
pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, F>
where
F: FnMut(&Janet) -> bool,
{
self.as_ref().rsplit(pred)
}
/// Creates an iterator over subslices separated by elements that match
/// `pred`, limited to returning at most `n` items. The matched element is
/// not contained in the subslices.
///
/// The last element returned, if any, will contain the remainder of the
/// tuple.
///
/// # Examples
///
/// Print the tuple split once by numbers divisible by 3 (i.e., `[10, 40]`,
/// `[20, 60, 50]`):
///
/// ```
/// use janetrs::{tuple, Janet, TaggedJanet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![10, 40, 30, 20, 60, 50];
///
/// for group in v.splitn(2, |j| match j.unwrap() {
/// TaggedJanet::Number(num) => num as i64 % 3 == 0,
/// _ => false,
/// }) {
/// println!("{:?}", group);
/// }
/// ```
#[inline]
pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, F>
where
F: FnMut(&Janet) -> bool,
{
self.as_ref().splitn(n, pred)
}
/// Returns an iterator over subslices separated by elements that match
/// `pred` limited to returning at most `n` items. This starts at the end of
/// the tuple and works backwards. The matched element is not contained in
/// the subslices.
///
/// The last element returned, if any, will contain the remainder of the
/// tuple.
///
/// # Examples
///
/// Print the tuple split once, starting from the end, by numbers divisible
/// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
///
/// ```
/// use janetrs::{tuple, Janet, TaggedJanet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let v = tuple![10, 40, 30, 20, 60, 50];
///
/// for group in v.rsplitn(2, |j| match j.unwrap() {
/// TaggedJanet::Number(num) => num as i64 % 3 == 0,
/// _ => false,
/// }) {
/// println!("{:?}", group);
/// }
/// ```
#[inline]
pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, F>
where
F: FnMut(&Janet) -> bool,
{
self.as_ref().rsplitn(n, pred)
}
/// Return a raw pointer to the tuple raw structure.
///
/// The caller must ensure that the fiber outlives the pointer this function returns,
/// or else it will end up pointing to garbage.
#[inline]
#[must_use]
pub const fn as_raw(&self) -> *const CJanet {
self.raw
}
/// Return a raw pointer to the tuple first data.
///
/// The caller must ensure that the array outlives the pointer this function returns,
/// or else it will end up pointing to garbage.
#[inline]
#[must_use]
pub fn as_ptr(&self) -> *const Janet {
self.raw as _
}
}
impl Debug for JanetTuple<'_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl Clone for JanetTuple<'_> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
let len = self.len();
let mut clone = Self::builder(len);
for elem in self.into_iter().copied() {
clone = clone.put(elem);
}
clone.finalize()
}
}
impl PartialOrd for JanetTuple<'_> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for JanetTuple<'_> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
use core::cmp::Ordering::{Equal, Greater, Less};
match self.len().cmp(&other.len()) {
x @ (Less | Greater) => x,
Equal => {
for (s, o) in self.iter().zip(other.iter()) {
match s.cmp(o) {
x @ (Less | Greater) => return x,
Equal => continue,
}
}
Equal
},
}
}
}
impl PartialEq for JanetTuple<'_> {
#[inline]
fn eq(&self, other: &Self) -> bool {
// if the pointer is the same, one are equal to the other
if self.raw.eq(&other.raw) {
return true;
}
// If the hash is the same
// SAFETY: Janet tuple must always be a valid pointer
if self.head().hash.eq(&self.head().hash) {
return true;
}
// if they have the same length, check value by value
if self.len().eq(&other.len()) {
return self.iter().zip(other.iter()).all(|(s, o)| s.eq(o));
}
// otherwise it's false
false
}
}
impl Eq for JanetTuple<'_> {}
impl super::DeepEq<JanetArray<'_>> for JanetTuple<'_> {
#[inline]
fn deep_eq(&self, other: &JanetArray<'_>) -> bool {
other.deep_eq(self)
}
}
impl Default for JanetTuple<'_> {
#[inline]
fn default() -> Self {
crate::tuple![]
}
}
impl AsRef<[Janet]> for JanetTuple<'_> {
#[inline]
fn as_ref(&self) -> &[Janet] {
// SAFETY: Janet uses i32 as max size for all collections and indexing, so it always has
// len lesser than isize::MAX
unsafe { core::slice::from_raw_parts(self.raw as *const _, self.len() as usize) }
}
}
impl From<JanetArray<'_>> for JanetTuple<'_> {
#[inline]
fn from(arr: JanetArray<'_>) -> Self {
arr.into_iter().collect()
}
}
impl From<&JanetArray<'_>> for JanetTuple<'_> {
#[inline]
fn from(arr: &JanetArray<'_>) -> Self {
arr.into_iter().collect()
}
}
impl<'data> IntoIterator for JanetTuple<'data> {
type IntoIter = IntoIter<'data>;
type Item = Janet;
#[inline]
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
IntoIter {
tup: self,
index_head: 0,
index_tail: len,
}
}
}
impl<'a, 'data> IntoIterator for &'a JanetTuple<'data> {
type IntoIter = Iter<'a, 'data>;
type Item = &'a Janet;
#[inline]
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
Iter {
tup: self,
index_head: 0,
index_tail: len,
}
}
}
impl<U: Into<Janet>> FromIterator<U> for JanetTuple<'_> {
#[cfg_attr(feature = "inline-more", inline)]
fn from_iter<T: IntoIterator<Item = U>>(iter: T) -> Self {
let iter = iter.into_iter().collect::<JanetArray>().into_iter();
let (lower, upper) = iter.size_hint();
let mut new = if let Some(upper) = upper {
Self::builder(upper as i32)
} else if lower > 0 {
Self::builder(lower as i32)
} else {
Self::builder(20)
};
for i in iter {
new = new.put(i);
}
new.finalize()
}
}
impl Index<i32> for JanetTuple<'_> {
type Output = Janet;
/// Get a reference of the [`Janet`] hold by [`JanetTuple`] at `index`.
///
/// # Janet Panics
/// This function may Janet panic if try to access `index` out of the bounds
#[inline]
fn index(&self, index: i32) -> &Self::Output {
if index < 0 {
crate::jpanic!(
"index out of bounds: the index ({}) is negative and must be positive",
index
)
}
self.get(index).unwrap_or_else(|| {
crate::jpanic!(
"index out of bounds: the len is {} but the index is {}",
self.len(),
index
)
})
}
}
/// An iterator over a reference to the [`JanetTuple`] elements.
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Iter<'a, 'data> {
tup: &'a JanetTuple<'data>,
index_head: i32,
index_tail: i32,
}
impl Debug for Iter<'_, '_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.tup.as_ref()).finish()
}
}
impl<'a> Iterator for Iter<'a, '_> {
type Item = &'a Janet;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.index_head >= self.index_tail {
None
} else {
let ret = self.tup.get(self.index_head);
self.index_head += 1;
ret
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = (self.index_tail - self.index_head) as usize;
(exact, Some(exact))
}
}
impl DoubleEndedIterator for Iter<'_, '_> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
if self.index_head == self.index_tail {
None
} else {
self.index_tail -= 1;
self.tup.get(self.index_tail)
}
}
}
impl ExactSizeIterator for Iter<'_, '_> {}
impl FusedIterator for Iter<'_, '_> {}
/// An iterator that moves out of a [`JanetTuple`].
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IntoIter<'data> {
tup: JanetTuple<'data>,
index_head: i32,
index_tail: i32,
}
impl Debug for IntoIter<'_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.tup.as_ref()).finish()
}
}
impl Iterator for IntoIter<'_> {
type Item = Janet;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.index_head >= self.index_tail {
None
} else {
let ret = self.tup.get(self.index_head).copied();
self.index_head += 1;
ret
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = (self.index_tail - self.index_head) as usize;
(exact, Some(exact))
}
}
impl DoubleEndedIterator for IntoIter<'_> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
if self.index_head == self.index_tail {
None
} else {
self.index_tail -= 1;
self.tup.get(self.index_tail).copied()
}
}
}
impl ExactSizeIterator for IntoIter<'_> {}
impl FusedIterator for IntoIter<'_> {}
#[cfg(all(test, any(feature = "amalgation", feature = "link-system")))]
mod tests {
use super::*;
use crate::{client::JanetClient, tuple, *};
use alloc::vec;
#[test]
fn builder() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let tuple = JanetTuple::builder(0).finalize();
assert!(tuple.is_empty());
let tuple = JanetTuple::builder(3)
.put(Janet::number(10.0))
.put(Janet::nil())
.put(Janet::boolean(true))
.finalize();
assert_eq!(3, tuple.len());
Ok(())
}
#[test]
fn get() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let tuple = JanetTuple::builder(3)
.put(Janet::number(10.0))
.put(Janet::nil())
.put(Janet::boolean(true))
.finalize();
assert_eq!(None, tuple.get(-1));
assert_eq!(Some(&Janet::number(10.0)), tuple.get(0));
assert_eq!(Some(&Janet::nil()), tuple.get(1));
assert_eq!(Some(&Janet::boolean(true)), tuple.get(2));
assert_eq!(None, tuple.get(3));
Ok(())
}
#[test]
fn clone() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let tuple = JanetTuple::builder(3)
.put(Janet::number(10.0))
.put(Janet::nil())
.put(Janet::boolean(true))
.finalize();
let clone = tuple.clone();
assert_ne!(tuple.raw, clone.raw);
assert_eq!(tuple.get(-1), clone.get(-1));
assert_eq!(tuple.get(0), clone.get(0));
assert_eq!(tuple.get(1), clone.get(1));
assert_eq!(tuple.get(2), clone.get(2));
assert_eq!(tuple.get(3), clone.get(3));
Ok(())
}
#[test]
fn collect() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let vec = vec![Janet::nil(); 100];
let jtup: JanetTuple<'_> = vec.into_iter().collect();
assert_eq!(jtup.len(), 100);
assert!(jtup.iter().all(|j| j == Janet::nil()));
let vec = crate::array![101.0, "string", true];
let jtup: JanetTuple<'_> = vec.into_iter().collect();
assert_eq!(jtup.len(), 3);
let mut iter = jtup.iter();
assert_eq!(Some(&Janet::number(101.0)), iter.next());
assert_eq!(
Some(&Janet::string(JanetString::new("string"))),
iter.next()
);
assert_eq!(Some(&Janet::boolean(true)), iter.next());
assert_eq!(None, iter.next());
Ok(())
}
#[test]
fn iter_iterator() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let array = tuple![1, "hey", true];
let mut iter = array.iter();
assert_eq!(Some(&Janet::integer(1)), iter.next());
assert_eq!(Some(&Janet::from("hey")), iter.next());
assert_eq!(Some(&Janet::boolean(true)), iter.next());
assert_eq!(None, iter.next());
Ok(())
}
#[test]
fn iter_double_ended_iterator() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let numbers = tuple![1, 2, 3, 4, 5, 6];
let mut iter = numbers.iter();
assert_eq!(iter.len(), 6);
assert_eq!(Some(&Janet::integer(1)), iter.next());
assert_eq!(iter.len(), 5);
assert_eq!(Some(&Janet::integer(6)), iter.next_back());
assert_eq!(iter.len(), 4);
assert_eq!(Some(&Janet::integer(5)), iter.next_back());
assert_eq!(iter.len(), 3);
assert_eq!(Some(&Janet::integer(2)), iter.next());
assert_eq!(iter.len(), 2);
assert_eq!(Some(&Janet::integer(3)), iter.next());
assert_eq!(iter.len(), 1);
assert_eq!(Some(&Janet::integer(4)), iter.next());
assert_eq!(iter.len(), 0);
assert_eq!(None, iter.next());
assert_eq!(None, iter.next_back());
Ok(())
}
#[test]
fn intoiter_iterator() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let array = tuple![1, "hey", true];
let mut iter = array.into_iter();
assert_eq!(Some(Janet::integer(1)), iter.next());
assert_eq!(Some(Janet::from("hey")), iter.next());
assert_eq!(Some(Janet::boolean(true)), iter.next());
assert_eq!(None, iter.next());
Ok(())
}
#[test]
fn intoiter_double_ended_iterator() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let numbers = tuple![1, 2, 3, 4, 5, 6];
let mut iter = numbers.into_iter();
assert_eq!(iter.len(), 6);
assert_eq!(Some(Janet::integer(1)), iter.next());
assert_eq!(iter.len(), 5);
assert_eq!(Some(Janet::integer(6)), iter.next_back());
assert_eq!(iter.len(), 4);
assert_eq!(Some(Janet::integer(5)), iter.next_back());
assert_eq!(iter.len(), 3);
assert_eq!(Some(Janet::integer(2)), iter.next());
assert_eq!(iter.len(), 2);
assert_eq!(Some(Janet::integer(3)), iter.next());
assert_eq!(iter.len(), 1);
assert_eq!(Some(Janet::integer(4)), iter.next());
assert_eq!(iter.len(), 0);
assert_eq!(None, iter.next());
assert_eq!(None, iter.next_back());
Ok(())
}
#[test]
fn size_hint() -> Result<(), client::Error> {
let _client = JanetClient::init()?;
let mut iter = tuple![0; 100].into_iter();
// The code for all the iterators of the array are the same
assert_eq!(iter.len(), 100);
let _ = iter.next();
assert_eq!(iter.len(), 99);
let _ = iter.next_back();
assert_eq!(iter.len(), 98);
Ok(())
}
#[test]
fn compare() -> Result<(), client::Error> {
use core::cmp::Ordering::*;
let _client = JanetClient::init()?;
let test = tuple![1, 2, 3, 4, 5, 6];
let clone = test.clone();
assert_eq!(test.cmp(&clone), Equal);
let test2 = tuple![1, 2];
assert_eq!(test.cmp(&test2), Greater);
Ok(())
}
}