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
// SPDX-License-Identifier: GPL-2.0-or-later
// SPDX-FileCopyrightText: Copyright Andrew Tridgell <tridge@samba.org> 2002
// SPDX-FileCopyrightText: Copyright (C) 2017, 2023 Tsukasa OI <floss_ssdeep@irq.a4lg.com>
use crate::hash::FuzzyHashData;
use crate::hash::block::{
block_size, block_hash,
BlockSizeRelation,
BlockHashSize, ConstrainedBlockHashSize,
BlockHashSizes, ConstrainedBlockHashSizes
};
use crate::hash_dual::{
FuzzyHashDualData,
RleBlockSizeForBlockHash, ConstrainedRleBlockSizeForBlockHash
};
use crate::macros::{optionally_unsafe, invariant};
/// Module that contains position array-related traits and implementations.
pub mod position_array;
/// Test-only utilities.
#[cfg(any(test, doc))]
mod test_utils;
#[cfg(test)]
mod tests;
use position_array::{
BlockHashPositionArrayData,
BlockHashPositionArrayImpl,
BlockHashPositionArrayImplInternal,
BlockHashPositionArrayImplMutInternal,
BlockHashPositionArrayRef,
BlockHashPositionArrayMutRef,
};
#[cfg(feature = "unchecked")]
use position_array::BlockHashPositionArrayImplUnchecked;
/// An efficient position array-based fuzzy hash comparison target.
///
/// It can be built from a normalized [`FuzzyHashData`] object and represents
/// the normalized contents of two block hashes as two position arrays.
///
/// Although that this structure is large, it is particularly useful if
/// you compare many of fuzzy hashes and you can fix one of the operands
/// (this is usually over 10 times faster than batched `fuzzy_compare` calls
/// in ssdeep 2.13). Even if we generate this object each time we compare
/// two fuzzy hashes, it's usually faster than `fuzzy_compare` in ssdeep 2.13.
///
/// In fact, if you just compare two fuzzy hashes in this crate, a temporary
/// [`FuzzyHashCompareTarget`] object is created from either side
/// of the comparison.
///
/// See also: ["Fuzzy Hash Comparison" section of `FuzzyHashData`](FuzzyHashData#fuzzy-hash-comparison)
///
/// # Examples
///
/// ```rust
/// // Requires the global allocator to use `Vec` (default on std).
/// # #[cfg(feature = "alloc")]
/// # {
/// use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
///
/// // Brute force comparison
/// let hashes: Vec<FuzzyHash> = Vec::new();
/// /* ... add fuzzy hashes to `hashes` ... */
///
/// let mut target: FuzzyHashCompareTarget = FuzzyHashCompareTarget::new();
/// for hash1 in &hashes {
/// target.init_from(hash1);
/// for hash2 in &hashes {
/// let score = target.compare(hash2);
/// /* ... */
/// }
/// }
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct FuzzyHashCompareTarget {
/// The position array representation of block hash 1.
///
/// See also:
/// 1. [`BlockHashPositionArrayData`]
/// 2. [`BlockHashPositionArrayImpl`]
/// 3. [`block_hash_1()`](Self::block_hash_1())
blockhash1: [u64; block_hash::ALPHABET_SIZE],
/// The position array representation of block hash 2.
///
/// See also:
/// 1. [`BlockHashPositionArrayData`]
/// 2. [`BlockHashPositionArrayImpl`]
/// 3. [`block_hash_2()`](Self::block_hash_2())
blockhash2: [u64; block_hash::ALPHABET_SIZE],
/// Length of the block hash 1 (up to [`block_hash::FULL_SIZE`]).
///
/// See also: [`block_hash_1()`](Self::block_hash_1())
len_blockhash1: u8,
/// Length of the block hash 2 (up to [`block_hash::FULL_SIZE`]).
///
/// See also: [`block_hash_2()`](Self::block_hash_2())
len_blockhash2: u8,
/// *Base-2 logarithm* form of the actual block size.
///
/// See also: ["Block Size" section of `FuzzyHashData`](Self#block-size)
log_blocksize: u8,
}
cfg_if::cfg_if! {
if #[cfg(not(feature = "unchecked"))] {
/// The return type of [`FuzzyHashCompareTarget::block_hash_1()`] and
/// [`FuzzyHashCompareTarget::block_hash_2()`].
macro_rules! compare_target_block_hash_pub_impl {
($a:lifetime) => {
impl $a + BlockHashPositionArrayImpl
};
}
/// The return type of [`FuzzyHashCompareTarget::block_hash_1_internal()`]
/// and [`FuzzyHashCompareTarget::block_hash_2_internal()`].
macro_rules! compare_target_block_hash_priv_impl {
($a:lifetime) => {
impl $a + BlockHashPositionArrayImpl + BlockHashPositionArrayImplInternal
};
}
}
else {
/// The return type of [`FuzzyHashCompareTarget::block_hash_1()`] and
/// [`FuzzyHashCompareTarget::block_hash_2()`].
macro_rules! compare_target_block_hash_pub_impl {
($a:lifetime) => {
impl $a + BlockHashPositionArrayImpl + BlockHashPositionArrayImplUnchecked
};
}
/// The return type of [`FuzzyHashCompareTarget::block_hash_1_internal()`]
/// and [`FuzzyHashCompareTarget::block_hash_2_internal()`].
macro_rules! compare_target_block_hash_priv_impl {
($a:lifetime) => {
impl $a + BlockHashPositionArrayImpl + BlockHashPositionArrayImplUnchecked + BlockHashPositionArrayImplInternal
};
}
}
}
impl FuzzyHashCompareTarget {
/// The minimum length of the common substring to compute edit distance
/// between two block hashes.
///
/// Use [`block_hash::MIN_LCS_FOR_COMPARISON`] instead.
///
/// # Incompatibility Notice
///
/// This constant will be removed on the version 0.3.0.
#[deprecated]
pub const MIN_LCS_FOR_BLOCKHASH: usize = block_hash::MIN_LCS_FOR_COMPARISON;
/// The lower bound (inclusive) of the *base-2 logarithm* form of
/// the block size in which the score capping is no longer required.
///
/// If `log_block_size` is equal to or larger than this value and `len1` and
/// `len2` are at least [`block_hash::MIN_LCS_FOR_COMPARISON`] in size,
/// [`Self::score_cap_on_block_hash_comparison`]`(log_block_size, len1, len2)`
/// is guaranteed to be `100` or greater.
///
/// The score "cap" is computed as
/// `(1 << log_block_size) * min(len1, len2)`.
/// If this always guaranteed to be `100` or greater,
/// capping the score is not longer required.
///
/// # Backgrounds
///
/// ## Theorem
///
/// For all positive integers `a`, `b` and `c`, `a <= b * c` iff
/// `(a + b - 1) / b <= c` (where `ceil(a/b) == (a + b - 1) / b`).
///
/// This is proven by Z3 and (partially) Coq in the source code:
/// * Z3 + Python:
/// `dev/prover/compare/blocksize_capping_theorem.py`
/// * Coq (uses existing ceiling function instead of `(a + b - 1) / b`):
/// `dev/prover/compare/blocksize_capping_theorem.v`
///
/// ## The Minimum Score Cap
///
/// This is expressed as `(1 << log_block_size) * MIN_LCS_FOR_COMPARISON`
/// because both block hashes must at least as long as
/// [`block_hash::MIN_LCS_FOR_COMPARISON`] to perform edit distance-based
/// scoring.
///
/// ## Computing the Constant
///
/// Applying the theorem above,
/// `100 <= (1 << log_block_size) * MIN_LCS_FOR_COMPARISON`
/// is equivalent to
/// `(100 + MIN_LCS_FOR_COMPARISON - 1) / MIN_LCS_FOR_COMPARISON <= (1 << log_block_size)`.
///
/// This leads to the expression to define this constant.
pub const LOG_BLOCK_SIZE_CAPPING_BORDER: u8 =
((100 + block_hash::MIN_LCS_FOR_COMPARISON as u64 - 1) / block_hash::MIN_LCS_FOR_COMPARISON as u64)
.next_power_of_two().trailing_zeros() as u8;
/// Creates a new [`FuzzyHashCompareTarget`] object with empty contents.
///
/// This is equivalent to the fuzzy hash string `3::`.
#[inline]
pub fn new() -> Self {
FuzzyHashCompareTarget {
blockhash1: [0u64; block_hash::ALPHABET_SIZE],
blockhash2: [0u64; block_hash::ALPHABET_SIZE],
len_blockhash1: 0,
len_blockhash2: 0,
log_blocksize: 0,
}
}
/// The *base-2 logarithm* form of the comparison target's block size.
///
/// See also: ["Block Size" section of `FuzzyHashData`](FuzzyHashData#block-size)
#[inline(always)]
pub fn log_block_size(&self) -> u8 { self.log_blocksize }
/// The block size of the comparison target.
#[inline]
pub fn block_size(&self) -> u32 {
block_size::from_log_internal(self.log_blocksize)
}
/// Position array-based representation of the block hash 1.
///
/// This is the same as [`block_hash_1()`](Self::block_hash_1()) except that
/// it exposes some internals.
///
/// See also: [`block_hash_1()`](Self::block_hash_1())
///
/// # Examples (Public part)
///
/// Because this documentation test is not suitable for a part of the public
/// documentation, it is listed here.
///
/// ```
/// use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
///
/// let target = FuzzyHashCompareTarget::from(str::parse::<FuzzyHash>("3:ABCDEFGHIJKLMNOP:").unwrap());
/// let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let base_bh1_mod: &[u8] = &[1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; // [0] is replaced
/// let bh1 = target.block_hash_1();
///
/// assert!(bh1.is_valid()); // Should be always true
/// assert!(bh1.is_valid_and_normalized()); // Should be always true
/// assert_eq!(bh1.len(), base_bh1.len() as u8);
/// assert!( bh1.is_equiv(base_bh1));
/// assert!(!bh1.is_equiv(base_bh1_mod));
/// assert!(!bh1.is_equiv(&[0, 1, 2, 3, 4, 5, 6, 7])); // "ABCDEFGH" (subset)
/// assert!( bh1.has_common_substring(&[ 0, 1, 2, 3, 4, 5, 6, 7])); // 0..=6 or 1..=7 matches (enough length)
/// assert!(!bh1.has_common_substring(&[10, 11, 12, 13, 14, 15, 16, 17])); // 10..=15 matches but doesn't have enough length
/// assert_eq!(bh1.edit_distance(base_bh1), 0); // edit distance with itself
/// assert_eq!(bh1.edit_distance(base_bh1_mod), 2); // replace a character: cost 2
/// assert_eq!(bh1.score_strings_raw(base_bh1), 100); // compare with itself
/// assert_eq!(bh1.score_strings(base_bh1, 0), 16); // compare with itself, capped (block size 3)
///
/// #[cfg(feature = "unchecked")]
/// unsafe {
/// use ssdeep::internal_comparison::BlockHashPositionArrayImplUnchecked;
/// // Test unchecked counterparts
/// assert!( bh1.is_equiv_unchecked(base_bh1));
/// assert!(!bh1.is_equiv_unchecked(base_bh1_mod));
/// assert!(!bh1.is_equiv_unchecked(&[0, 1, 2, 3, 4, 5, 6, 7]));
/// assert!( bh1.has_common_substring_unchecked(&[ 0, 1, 2, 3, 4, 5, 6, 7]));
/// assert!(!bh1.has_common_substring_unchecked(&[10, 11, 12, 13, 14, 15, 16, 17]));
/// assert_eq!(bh1.edit_distance_unchecked(base_bh1), 0);
/// assert_eq!(bh1.edit_distance_unchecked(base_bh1_mod), 2);
/// assert_eq!(bh1.score_strings_raw_unchecked(base_bh1), 100);
/// assert_eq!(bh1.score_strings_unchecked(base_bh1, 0), 16);
/// }
/// ```
///
/// # Examples (Private part which should fail)
///
/// It allows access to internal functions of [`BlockHashPositionArrayImplInternal`].
///
/// In the examples below, it makes sure that they are not
/// accessible from outside.
///
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let target = FuzzyHashCompareTarget::from(str::parse::<FuzzyHash>("3:ABCDEFGHIJKLMNOP:").unwrap());
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert!(bh1.is_equiv_internal(base_bh1));
/// ```
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let target = FuzzyHashCompareTarget::from(str::parse::<FuzzyHash>("3:ABCDEFGHIJKLMNOP:").unwrap());
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert!(bh1.has_common_substring_internal(&[0, 1, 2, 3, 4, 5, 6, 7]));
/// ```
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let target = FuzzyHashCompareTarget::from(str::parse::<FuzzyHash>("3:ABCDEFGHIJKLMNOP:").unwrap());
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert_eq!(bh1.edit_distance_internal(base_bh1), 0);
/// ```
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let target = FuzzyHashCompareTarget::from(str::parse::<FuzzyHash>("3:ABCDEFGHIJKLMNOP:").unwrap());
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert_eq!(bh1.score_strings_raw_internal(base_bh1), 100);
/// ```
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let target = FuzzyHashCompareTarget::from(str::parse::<FuzzyHash>("3:ABCDEFGHIJKLMNOP:").unwrap());
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert_eq!(bh1.score_strings_internal(base_bh1, 0), 16);
/// ```
#[inline(always)]
fn block_hash_1_internal(&self) -> compare_target_block_hash_priv_impl!('_) {
BlockHashPositionArrayRef(&self.blockhash1, &self.len_blockhash1)
}
/// Position array-based representation of the block hash 1.
///
/// This method provices raw access to the internal efficient block hash
/// representation and fast bit-parallel string functions.
///
/// You are not recommended to use this unless
/// you know the internal details deeply.
///
/// The result has the same lifetime as this object and implements
/// following traits:
///
/// 1. [`BlockHashPositionArrayData`]
/// 2. [`BlockHashPositionArrayImpl`]
/// 3. [`BlockHashPositionArrayImplUnchecked`]
/// (only if the `unchecked` feature is enabled)
#[inline(always)]
pub fn block_hash_1(&self) -> compare_target_block_hash_pub_impl!('_) {
// Expose a subset of block_hash_1_internal()
self.block_hash_1_internal()
}
/// Position array-based representation of the block hash 1.
///
/// This is internal only *and* mutable.
///
/// See also: [`block_hash_1()`](Self::block_hash_1())
///
/// # Examples (That should fail)
///
/// In the examples below, it makes sure that they are not
/// accessible from outside.
///
/// It allows access to internal functions of
/// [`BlockHashPositionArrayImplMut`](crate::compare::position_array::BlockHashPositionArrayImplMut)
/// and [`BlockHashPositionArrayImplMutInternal`].
///
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let mut target = FuzzyHashCompareTarget::new();
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert!(bh1.init_from(base_bh1));
/// ```
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let mut target = FuzzyHashCompareTarget::new();
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert!(bh1.set_len_internal(16));
/// ```
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let mut target = FuzzyHashCompareTarget::new();
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert!(bh1.clear_representation_only());
/// ```
/// ```compile_fail
/// # use ssdeep::{FuzzyHash, FuzzyHashCompareTarget};
/// # use ssdeep::internal_comparison::{BlockHashPositionArrayData, BlockHashPositionArrayImpl};
/// # let mut target = FuzzyHashCompareTarget::new();
/// # let base_bh1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// let bh1 = target.block_hash_1();
/// assert!(bh1.init_from_partial(base_bh1));
/// ```
#[inline(always)]
fn block_hash_1_mut(&mut self)
-> impl '_ + BlockHashPositionArrayImpl + BlockHashPositionArrayImplMutInternal
{
BlockHashPositionArrayMutRef(&mut self.blockhash1, &mut self.len_blockhash1)
}
/// Position array-based representation of the block hash 2.
///
/// This is the same as [`block_hash_2()`](Self::block_hash_2()) except that
/// it exposes some internals.
///
/// See also: [`block_hash_1_internal()`](Self::block_hash_1_internal())
#[inline(always)]
fn block_hash_2_internal(&self) -> compare_target_block_hash_priv_impl!('_) {
BlockHashPositionArrayRef(&self.blockhash2, &self.len_blockhash2)
}
/// Position array-based representation of the block hash 2.
///
/// See also: [`block_hash_1()`](Self::block_hash_1())
#[inline(always)]
pub fn block_hash_2(&self) -> compare_target_block_hash_pub_impl!('_) {
// Expose a subset of block_hash_2_internal()
self.block_hash_2_internal()
}
/// Position array-based representation of the block hash 2.
///
/// This is internal only *and* mutable.
///
/// See also: [`block_hash_1_mut()`](Self::block_hash_1_mut())
#[inline(always)]
fn block_hash_2_mut(&mut self)
-> impl '_ + BlockHashPositionArrayImpl + BlockHashPositionArrayImplMutInternal
{
BlockHashPositionArrayMutRef(&mut self.blockhash2, &mut self.len_blockhash2)
}
/// Performs full equality checking of the internal structure.
///
/// This type intentionally lacks the implementation of [`PartialEq`]
/// because of its large size. However, there's a case where we need to
/// compare two comparison targets.
///
/// The primary purpose of this is debugging and it compares all internal
/// members inside the structure (just like auto-generated
/// [`PartialEq::eq()`]).
///
/// Note that, despite that it is only relevant to users when the
/// `unchecked` feature is enabled but made public without any features
/// because this method is not *unsafe*.
pub fn full_eq(&self, other: &Self) -> bool {
// The contents of this method is auto-generated by rust-analyzer
// (the only modification is the indentation).
self.blockhash1 == other.blockhash1 &&
self.blockhash2 == other.blockhash2 &&
self.len_blockhash1 == other.len_blockhash1 &&
self.len_blockhash2 == other.len_blockhash2 &&
self.log_blocksize == other.log_blocksize
}
/// Initialize the object from a given fuzzy hash
/// (without clearing the position arrays).
///
/// This method is intended to be used just after clearing the position
/// arrays (i.e. just after the initialization).
#[inline]
fn init_from_partial<const S1: usize, const S2: usize>(
&mut self,
hash: impl AsRef<FuzzyHashData<S1, S2, true>>
)
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let hash = hash.as_ref();
debug_assert!((hash.len_blockhash1 as usize) <= S1);
debug_assert!((hash.len_blockhash2 as usize) <= S2);
debug_assert!(block_size::is_log_valid(hash.log_blocksize));
self.len_blockhash1 = hash.len_blockhash1;
self.len_blockhash2 = hash.len_blockhash2;
self.log_blocksize = hash.log_blocksize;
// Initialize position arrays based on the original block hashes
self.block_hash_1_mut().init_from_partial(hash.block_hash_1());
self.block_hash_2_mut().init_from_partial(hash.block_hash_2());
}
/// Initialize the object from a given fuzzy hash.
#[inline]
pub fn init_from<const S1: usize, const S2: usize>(
&mut self,
hash: impl AsRef<FuzzyHashData<S1, S2, true>>
)
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.block_hash_1_mut().clear_representation_only();
self.block_hash_2_mut().clear_representation_only();
self.init_from_partial(hash);
}
/// Compare whether two fuzzy hashes are equivalent
/// (except for their block size).
#[inline]
fn is_equiv_except_block_size<const S1: usize, const S2: usize>(
&self,
hash: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let hash = hash.as_ref();
self.block_hash_1_internal().is_equiv_internal(hash.block_hash_1()) &&
self.block_hash_2_internal().is_equiv_internal(hash.block_hash_2())
}
/// Compare whether two fuzzy hashes are equivalent.
#[inline(always)]
pub fn is_equiv<const S1: usize, const S2: usize>(
&self,
hash: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let hash = hash.as_ref();
if self.log_blocksize != hash.log_blocksize { return false; }
self.is_equiv_except_block_size(hash)
}
/// The internal implementation of [`Self::score_cap_on_block_hash_comparison_unchecked()`].
#[inline(always)]
fn score_cap_on_block_hash_comparison_internal(
log_block_size: u8,
len_block_hash_lhs: u8,
len_block_hash_rhs: u8
) -> u32
{
optionally_unsafe! {
invariant!(log_block_size < FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER);
}
(1u32 << log_block_size) * u32::min(len_block_hash_lhs as u32, len_block_hash_rhs as u32)
}
/// Returns the "score cap" for a given block size and two block hash
/// lengths, assuming that block size is small enough so that an arithmetic
/// overflow will not occur.
///
/// # Safety
///
/// If `log_block_size` is equal to or larger than
/// [`FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER`](Self::LOG_BLOCK_SIZE_CAPPING_BORDER)
/// and/or both lengths are too large, it may cause an
/// arithmetic overflow and return an useless value.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn score_cap_on_block_hash_comparison_unchecked(
log_block_size: u8,
len_block_hash_lhs: u8,
len_block_hash_rhs: u8
) -> u32
{
Self::score_cap_on_block_hash_comparison_internal(
log_block_size,
len_block_hash_lhs,
len_block_hash_rhs
)
}
/// Returns the "score cap" for a given block size and
/// two block hash lengths.
///
/// The internal block hash comparison method "caps" the score to prevent
/// exaggregating the matches that are not meaningful enough. This behavior
/// depends on the block size (the "cap" gets higher as the block size gets
/// higher) and the minimum of block hash lengths.
///
/// The result is not always guaranteed to be in `0..=100` but `100` or
/// higher means that we don't need any score capping.
#[inline(always)]
pub fn score_cap_on_block_hash_comparison(
log_block_size: u8,
len_block_hash_lhs: u8,
len_block_hash_rhs: u8
) -> u32
{
if log_block_size >= FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER {
100
}
else {
Self::score_cap_on_block_hash_comparison_internal(
log_block_size,
len_block_hash_lhs,
len_block_hash_rhs
)
}
}
}
impl Default for FuzzyHashCompareTarget {
fn default() -> Self {
Self::new()
}
}
impl FuzzyHashCompareTarget {
/// Performs full validity checking of the internal structure.
///
/// The primary purpose of this is debugging and it should always
/// return [`true`] unless...
///
/// 1. There is a bug in this crate, corrupting this structure or
/// 2. A memory corruption is occurred somewhere else.
///
/// Because of its purpose, this method is not designed to be fast.
pub fn is_valid(&self) -> bool {
block_size::is_log_valid(self.log_blocksize)
&& self.block_hash_1_internal().is_valid_and_normalized()
&& self.block_hash_2_internal().is_valid_and_normalized()
}
/// The internal implementation of [`Self::compare_unequal_near_eq_unchecked()`].
#[inline]
fn compare_unequal_near_eq_internal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
debug_assert!(!self.is_equiv(other));
debug_assert!(block_size::is_near_eq(self.log_blocksize, other.log_blocksize));
u32::max(
self.block_hash_1_internal().score_strings_internal(
other.block_hash_1(),
self.log_blocksize
),
self.block_hash_2_internal().score_strings_internal(
other.block_hash_2(),
self.log_blocksize + 1
)
)
}
/// Compare two fuzzy hashes assuming both are different and their
/// block sizes have a relation of [`BlockSizeRelation::NearEq`].
///
/// # Safety
///
/// * Both fuzzy hashes must be different.
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearEq`].
///
/// If they are not satisfied, it will return a meaningless score.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn compare_unequal_near_eq_unchecked<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.compare_unequal_near_eq_internal(other)
}
/// *Slow*: Compare two fuzzy hashes assuming both are different and
/// their block sizes have a relation of [`BlockSizeRelation::NearEq`].
///
/// # Usage Constraints
///
/// * Both fuzzy hashes must be different.
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearEq`].
///
/// # Performance Consideration
///
/// This method's performance is not good enough (because of constraint
/// checking).
///
/// Use those instead:
/// * [`compare_near_eq()`](Self::compare_near_eq()) (safe Rust)
/// * [`compare_unequal_near_eq_unchecked()`](Self::compare_unequal_near_eq_unchecked())
/// (unsafe Rust)
#[inline(always)]
pub fn compare_unequal_near_eq<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
assert!(!self.is_equiv(other));
assert!(block_size::is_near_eq(self.log_blocksize, other.log_blocksize));
self.compare_unequal_near_eq_internal(other)
}
/// The internal implementation of [`Self::compare_near_eq_unchecked()`].
#[inline]
fn compare_near_eq_internal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
debug_assert!(block_size::is_near_eq(self.log_blocksize, other.log_blocksize));
if self.is_equiv_except_block_size(other) { return 100; }
self.compare_unequal_near_eq_internal(other)
}
/// Compare two fuzzy hashes assuming their block sizes have
/// a relation of [`BlockSizeRelation::NearEq`].
///
/// # Safety
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearEq`].
///
/// If the condition above is not satisfied, it will return
/// a meaningless score.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn compare_near_eq_unchecked<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.compare_near_eq_internal(other)
}
/// Compare two fuzzy hashes assuming their block sizes have
/// a relation of [`BlockSizeRelation::NearEq`].
///
/// # Usage Constraints
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearEq`].
#[inline(always)]
pub fn compare_near_eq<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
assert!(block_size::is_near_eq(self.log_blocksize, other.log_blocksize));
self.compare_near_eq_internal(other)
}
/// The internal implementation of [`Self::compare_unequal_near_lt_unchecked()`].
#[inline(always)]
fn compare_unequal_near_lt_internal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
debug_assert!(block_size::is_near_lt(self.log_blocksize, other.log_blocksize));
self.block_hash_2_internal().score_strings_internal(
other.block_hash_1(),
other.log_blocksize
)
}
/// Compare two fuzzy hashes assuming both are different and their
/// block sizes have a relation of [`BlockSizeRelation::NearLt`].
///
/// # Safety
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearLt`].
///
/// If they are not satisfied, it will return a meaningless score.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn compare_unequal_near_lt_unchecked<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.compare_unequal_near_lt_internal(other)
}
/// Compare two fuzzy hashes assuming both are different and their
/// block sizes have a relation of [`BlockSizeRelation::NearLt`].
///
/// # Usage Constraints
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearLt`].
#[inline(always)]
pub fn compare_unequal_near_lt<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
assert!(block_size::is_near_lt(self.log_blocksize, other.log_blocksize));
self.compare_unequal_near_lt_internal(other)
}
/// The internal implementation of [`Self::compare_unequal_near_gt_unchecked()`].
#[inline(always)]
fn compare_unequal_near_gt_internal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
debug_assert!(block_size::is_near_gt(self.log_blocksize, other.log_blocksize));
self.block_hash_1_internal().score_strings_internal(
other.block_hash_2(),
self.log_blocksize
)
}
/// Compare two fuzzy hashes assuming both are different and their
/// block sizes have a relation of [`BlockSizeRelation::NearGt`].
///
/// # Safety
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearGt`].
///
/// If they are not satisfied, it will return a meaningless score.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn compare_unequal_near_gt_unchecked<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.compare_unequal_near_gt_internal(other)
}
/// Compare two fuzzy hashes assuming both are different and their
/// block sizes have a relation of [`BlockSizeRelation::NearGt`].
///
/// # Usage Constraints
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearGt`].
#[inline(always)]
pub fn compare_unequal_near_gt<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
assert!(block_size::is_near_gt(self.log_blocksize, other.log_blocksize));
self.compare_unequal_near_gt_internal(other)
}
/// The internal implementation of [`Self::compare_unequal_unchecked()`].
#[inline]
fn compare_unequal_internal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
debug_assert!(!self.is_equiv(other));
match block_size::compare_sizes(self.log_blocksize, other.log_blocksize) {
BlockSizeRelation::Far => 0,
BlockSizeRelation::NearEq => self.compare_unequal_near_eq_internal(other),
BlockSizeRelation::NearLt => self.compare_unequal_near_lt_internal(other),
BlockSizeRelation::NearGt => self.compare_unequal_near_gt_internal(other),
}
}
/// Compare two normalized fuzzy hashes assuming both are different.
///
/// # Safety
///
/// * Both fuzzy hashes (`self` and `other`) must be different.
///
/// If the condition above is not satisfied, it will return
/// a meaningless score.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn compare_unequal_unchecked<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.compare_unequal_internal(other)
}
/// *Slow*: Compare two normalized fuzzy hashes assuming
/// both are different.
///
/// # Usage Constraints
///
/// * Both fuzzy hashes (`self` and `other`) must be different.
///
/// # Performance Consideration
///
/// This method's performance is not good enough (because of the constraint
/// checking).
///
/// Use those instead:
/// * [`compare()`](Self::compare()) (safe Rust)
/// * [`compare_unequal_unchecked()`](Self::compare_unequal_unchecked())
/// (unsafe Rust)
#[inline(always)]
pub fn compare_unequal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
assert!(!self.is_equiv(other));
self.compare_unequal_internal(other)
}
/// Compares two normalized fuzzy hashes.
#[inline]
pub fn compare<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> u32
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
match block_size::compare_sizes(self.log_blocksize, other.log_blocksize) {
BlockSizeRelation::Far => 0,
BlockSizeRelation::NearEq => self.compare_near_eq_internal(other),
BlockSizeRelation::NearLt => self.compare_unequal_near_lt_internal(other),
BlockSizeRelation::NearGt => self.compare_unequal_near_gt_internal(other),
}
}
/// The internal implementation of [`Self::is_comparison_candidate_near_eq_unchecked()`].
#[inline]
fn is_comparison_candidate_near_eq_internal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
debug_assert!(block_size::is_near_eq(self.log_blocksize, other.log_blocksize));
self.block_hash_1_internal().has_common_substring_internal(other.block_hash_1()) ||
self.block_hash_2_internal().has_common_substring_internal(other.block_hash_2())
}
/// Tests whether `other` is a candidate for edit distance-based comparison
/// assuming that their block sizes have a relation of
/// [`BlockSizeRelation::NearEq`].
///
/// See also: [`is_comparison_candidate()`](Self::is_comparison_candidate())
///
/// # Safety
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearEq`].
///
/// If the condition above is not satisfied, it will return
/// a meaningless value.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn is_comparison_candidate_near_eq_unchecked<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.is_comparison_candidate_near_eq_internal(other)
}
/// Tests whether `other` is a candidate for edit distance-based comparison
/// assuming that their block sizes have a relation of
/// [`BlockSizeRelation::NearEq`].
///
/// See also: [`is_comparison_candidate()`](Self::is_comparison_candidate())
///
/// # Usage Constraints
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearEq`].
#[inline(always)]
pub fn is_comparison_candidate_near_eq<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
assert!(block_size::is_near_eq(self.log_blocksize, other.log_blocksize));
self.is_comparison_candidate_near_eq_internal(other)
}
/// The internal implementation of [`Self::is_comparison_candidate_near_lt_unchecked()`].
#[inline]
fn is_comparison_candidate_near_lt_internal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
debug_assert!(block_size::is_near_lt(self.log_blocksize, other.log_blocksize));
self.block_hash_2_internal().has_common_substring_internal(other.block_hash_1())
}
/// Tests whether `other` is a candidate for edit distance-based comparison
/// assuming that their block sizes have a relation of
/// [`BlockSizeRelation::NearLt`].
///
/// See also: [`is_comparison_candidate()`](Self::is_comparison_candidate())
///
/// # Safety
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearLt`].
///
/// If the condition above is not satisfied, it will return
/// a meaningless value.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn is_comparison_candidate_near_lt_unchecked<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.is_comparison_candidate_near_lt_internal(other)
}
/// Tests whether `other` is a candidate for edit distance-based comparison
/// assuming that their block sizes have a relation of
/// [`BlockSizeRelation::NearLt`].
///
/// See also: [`is_comparison_candidate()`](Self::is_comparison_candidate())
///
/// # Usage Constraints
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearLt`].
#[inline(always)]
pub fn is_comparison_candidate_near_lt<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
assert!(block_size::is_near_lt(self.log_blocksize, other.log_blocksize));
self.is_comparison_candidate_near_lt_internal(other)
}
/// The internal implementation of [`Self::is_comparison_candidate_near_gt_unchecked()`].
#[inline]
fn is_comparison_candidate_near_gt_internal<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
debug_assert!(block_size::is_near_gt(self.log_blocksize, other.log_blocksize));
self.block_hash_1_internal().has_common_substring_internal(other.block_hash_2())
}
/// Tests whether `other` is a candidate for edit distance-based comparison
/// assuming that their block sizes have a relation of
/// [`BlockSizeRelation::NearGt`].
///
/// See also: [`is_comparison_candidate()`](Self::is_comparison_candidate())
///
/// # Safety
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearGt`].
///
/// If the condition above is not satisfied, it will return
/// a meaningless value.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn is_comparison_candidate_near_gt_unchecked<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
self.is_comparison_candidate_near_gt_internal(other)
}
/// Tests whether `other` is a candidate for edit distance-based comparison
/// assuming that their block sizes have a relation of
/// [`BlockSizeRelation::NearGt`].
///
/// See also: [`is_comparison_candidate()`](Self::is_comparison_candidate())
///
/// # Usage Constraints
///
/// * Both fuzzy hashes (`self` and `other`) must have
/// block size relation of [`BlockSizeRelation::NearGt`].
#[inline(always)]
pub fn is_comparison_candidate_near_gt<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
assert!(block_size::is_near_gt(self.log_blocksize, other.log_blocksize));
self.is_comparison_candidate_near_gt_internal(other)
}
/// Tests whether `other` is a candidate for edit distance-based comparison.
///
/// If this function returns [`false`] **and** `self` and `other` are not
/// [equivalent](Self::is_equiv), their similarity will be calculated to 0.
///
/// # Use Case (Example)
///
/// This operation is useful to divide a set of *unique* (normalized)
/// fuzzy hashes into smaller distinct sets. The similarity score can be
/// non-zero if and only if two fuzzy hashes belong to the same set.
///
/// # Safety (Warning)
///
/// This function (and its variants) can return [`false`] if `self` and
/// `other` are equivalent (the base fuzzy hash object of `self` and `other`
/// are the same and their similarity score is 100).
///
/// Because of this, we have to use a set of *unique* fuzzy hash values
/// on the use case above to prevent false-negative matches.
#[inline]
pub fn is_comparison_candidate<const S1: usize, const S2: usize>(
&self,
other: impl AsRef<FuzzyHashData<S1, S2, true>>
) -> bool
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
let other = other.as_ref();
match block_size::compare_sizes(self.log_blocksize, other.log_blocksize) {
BlockSizeRelation::Far => false,
BlockSizeRelation::NearEq => self.is_comparison_candidate_near_eq_internal(other),
BlockSizeRelation::NearLt => self.is_comparison_candidate_near_lt_internal(other),
BlockSizeRelation::NearGt => self.is_comparison_candidate_near_gt_internal(other),
}
}
}
impl<const S1: usize, const S2: usize>
core::convert::From<FuzzyHashData<S1, S2, true>> for FuzzyHashCompareTarget
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
#[allow(clippy::needless_borrow)]
#[inline]
fn from(value: FuzzyHashData<S1, S2, true>) -> Self {
let mut dest: Self = Self::new();
dest.init_from_partial(&value);
dest
}
}
impl<const S1: usize, const S2: usize>
core::convert::From<&FuzzyHashData<S1, S2, true>> for FuzzyHashCompareTarget
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
#[inline]
fn from(value: &FuzzyHashData<S1, S2, true>) -> Self {
let mut dest: Self = Self::new();
dest.init_from_partial(value);
dest
}
}
impl<const S1: usize, const S2: usize, const C1: usize, const C2: usize>
core::convert::From<FuzzyHashDualData<S1, S2, C1, C2>> for FuzzyHashCompareTarget
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes,
RleBlockSizeForBlockHash<S1, C1>: ConstrainedRleBlockSizeForBlockHash,
RleBlockSizeForBlockHash<S2, C2>: ConstrainedRleBlockSizeForBlockHash
{
#[allow(clippy::needless_borrow)]
#[inline]
fn from(value: FuzzyHashDualData<S1, S2, C1, C2>) -> Self {
Self::from(value.as_ref())
}
}
impl<const S1: usize, const S2: usize, const C1: usize, const C2: usize>
core::convert::From<&FuzzyHashDualData<S1, S2, C1, C2>> for FuzzyHashCompareTarget
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes,
RleBlockSizeForBlockHash<S1, C1>: ConstrainedRleBlockSizeForBlockHash,
RleBlockSizeForBlockHash<S2, C2>: ConstrainedRleBlockSizeForBlockHash
{
#[allow(clippy::needless_borrow)]
#[inline]
fn from(value: &FuzzyHashDualData<S1, S2, C1, C2>) -> Self {
Self::from(value.as_ref())
}
}
/// Additional implementation for normalized fuzzy hashes,
/// enabling comparison between two fuzzy hashes directly.
impl<const S1: usize, const S2: usize> FuzzyHashData<S1, S2, true>
where
BlockHashSize<S1>: ConstrainedBlockHashSize,
BlockHashSize<S2>: ConstrainedBlockHashSize,
BlockHashSizes<S1, S2>: ConstrainedBlockHashSizes
{
/// Compare two fuzzy hashes and retrieves the similarity score.
#[inline]
pub fn compare(&self, other: impl AsRef<Self>) -> u32 {
let target = FuzzyHashCompareTarget::from(self);
target.compare(other.as_ref())
}
/// The internal implementation of [`Self::compare_unequal_unchecked()`].
#[inline]
fn compare_unequal_internal(&self, other: impl AsRef<Self>) -> u32 {
let other = other.as_ref();
debug_assert!(self != other);
let target = FuzzyHashCompareTarget::from(self);
target.compare_unequal_internal(other)
}
/// Compare two fuzzy hashes assuming both are different.
///
/// # Safety
///
/// * `self` and `other` must be different.
///
/// If the condition above is not satisfied, it will return
/// a meaningless score.
#[cfg(feature = "unchecked")]
#[allow(unsafe_code)]
#[inline(always)]
pub unsafe fn compare_unequal_unchecked(&self, other: impl AsRef<Self>) -> u32 {
self.compare_unequal_internal(other)
}
/// *Slow*: Compare two fuzzy hashes assuming both are different.
///
/// # Usage Constraints
///
/// * `self` and `other` must be different.
///
/// # Performance Consideration
///
/// This method's performance is not good enough (because of constraint
/// checking).
///
/// Use those instead:
/// * [`compare()`](Self::compare()) (safe Rust)
/// * [`compare_unequal_unchecked()`](Self::compare_unequal_unchecked())
/// (unsafe Rust)
#[inline(always)]
pub fn compare_unequal(&self, other: impl AsRef<Self>) -> u32 {
let other = other.as_ref();
assert!(self != other);
self.compare_unequal_internal(other)
}
}
/// Constant assertions related to this module
#[doc(hidden)]
mod const_asserts {
use super::*;
use static_assertions::{const_assert, const_assert_eq};
/// Check whether a given block size requires no score capping.
#[allow(dead_code)] // to avoid false error
const fn is_log_block_size_needs_no_capping(log_block_size: u8) -> bool {
// Test whether score_cap in score_strings method is equal to
// or greater than 100 (meaning, no capping is required).
(100 + block_hash::MIN_LCS_FOR_COMPARISON as u64 - 1) /
block_hash::MIN_LCS_FOR_COMPARISON as u64
<= block_size::from_log_internal(log_block_size) as u64 / block_size::MIN as u64
}
// Compare with the precomputed value
// (block_size / block_size::MIN >= 15, log_block_size >= 4 [2^log_block_size >= 16])
const_assert_eq!(FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER, 4);
// Regular tests.
const_assert!(block_size::is_log_valid(FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER));
const_assert!(!is_log_block_size_needs_no_capping(FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER - 1));
const_assert!( is_log_block_size_needs_no_capping(FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER));
// Regular tests (dynamic)
// grcov-excl-br-start
#[cfg(test)]
#[test]
fn log_block_size_capping_border_is_correct() {
assert!(!is_log_block_size_needs_no_capping(FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER - 1));
assert!( is_log_block_size_needs_no_capping(FuzzyHashCompareTarget::LOG_BLOCK_SIZE_CAPPING_BORDER));
}
// grcov-excl-br-end
}