trie.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /**
  2. * Hostbane-Optimized Trie based on Mnemonist Trie
  3. */
  4. import { fastStringCompare } from './misc';
  5. import util from 'node:util';
  6. import { noop } from 'foxts/noop';
  7. import { fastStringArrayJoin } from 'foxts/fast-string-array-join';
  8. import FIFO from 'fast-fifo';
  9. import { deleteBit, getBit, missingBit, setBit } from 'foxts/bitwise';
  10. const START = 1 << 1;
  11. const INCLUDE_ALL_SUBDOMAIN = 1 << 2;
  12. type TrieNode<Meta = any> = [
  13. flag: number, /** end, includeAllSubdomain (.example.org, ||example.com) */
  14. TrieNode | null, /** parent */
  15. Map<string, TrieNode>, /** children */
  16. Meta /** meta */
  17. ];
  18. function deepTrieNodeToJSON(node: TrieNode,
  19. unpackMeta: ((meta?: any) => string) | undefined) {
  20. const obj: Record<string, any> = {};
  21. obj['[start]'] = getBit(node[0], START);
  22. obj['[subdomain]'] = getBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  23. if (node[3] != null) {
  24. if (unpackMeta) {
  25. obj['[meta]'] = unpackMeta(node[3]);
  26. } else {
  27. obj['[meta]'] = node[3];
  28. }
  29. }
  30. node[2].forEach((value, key) => {
  31. obj[key] = deepTrieNodeToJSON(value, unpackMeta);
  32. });
  33. return obj;
  34. }
  35. const createNode = <Meta = any>(parent: TrieNode | null = null): TrieNode => [1, parent, new Map<string, TrieNode>(), null] as TrieNode<Meta>;
  36. function hostnameToTokens(hostname: string, hostnameFromIndex: number): string[] {
  37. const tokens = hostname.split('.');
  38. const results: string[] = [];
  39. let token = '';
  40. for (let i = hostnameFromIndex, l = tokens.length; i < l; i++) {
  41. token = tokens[i];
  42. if (token.length > 0) {
  43. results.push(token);
  44. } else {
  45. throw new TypeError(JSON.stringify({ hostname, hostnameFromIndex }, null, 2));
  46. }
  47. }
  48. return results;
  49. }
  50. function walkHostnameTokens(hostname: string, onToken: (token: string) => boolean | null, hostnameFromIndex: number): boolean | null {
  51. const tokens = hostname.split('.');
  52. const l = tokens.length - 1;
  53. // we are at the first of hostname, no splitor there
  54. let token = '';
  55. for (let i = l; i >= hostnameFromIndex; i--) {
  56. token = tokens[i];
  57. if (token.length > 0) {
  58. const t = onToken(token);
  59. if (t === null) {
  60. return null;
  61. }
  62. // if the callback returns true, we should skip the rest
  63. if (t) {
  64. return true;
  65. }
  66. }
  67. }
  68. return false;
  69. }
  70. interface FindSingleChildLeafResult<Meta> {
  71. node: TrieNode<Meta>,
  72. toPrune: TrieNode<Meta> | null,
  73. tokenToPrune: string | null,
  74. parent: TrieNode<Meta>
  75. }
  76. abstract class Triebase<Meta = any> {
  77. protected readonly $root: TrieNode<Meta> = createNode();
  78. protected $size = 0;
  79. get root() {
  80. return this.$root;
  81. }
  82. constructor(from?: string[] | Set<string> | null) {
  83. // Actually build trie
  84. if (Array.isArray(from)) {
  85. for (let i = 0, l = from.length; i < l; i++) {
  86. this.add(from[i]);
  87. }
  88. } else if (from) {
  89. from.forEach((value) => this.add(value));
  90. }
  91. }
  92. public abstract add(suffix: string, includeAllSubdomain?: boolean, meta?: Meta, hostnameFromIndex?: number): void;
  93. protected walkIntoLeafWithTokens(
  94. tokens: string[],
  95. onLoop: (node: TrieNode, parent: TrieNode, token: string) => void = noop
  96. ) {
  97. let node: TrieNode = this.$root;
  98. let parent: TrieNode = node;
  99. let token: string;
  100. let child: Map<string, TrieNode<Meta>> = node[2];
  101. // reverse lookup from end to start
  102. for (let i = tokens.length - 1; i >= 0; i--) {
  103. token = tokens[i];
  104. // if (token === '') {
  105. // break;
  106. // }
  107. parent = node;
  108. child = node[2];
  109. // cache node index access is 20% faster than direct access when doing twice
  110. if (child.has(token)) {
  111. node = child.get(token)!;
  112. } else {
  113. return null;
  114. }
  115. onLoop(node, parent, token);
  116. }
  117. return { node, parent };
  118. };
  119. protected walkIntoLeafWithSuffix(
  120. suffix: string,
  121. hostnameFromIndex: number,
  122. onLoop: (node: TrieNode, parent: TrieNode, token: string) => void = noop
  123. ) {
  124. let node: TrieNode = this.$root;
  125. let parent: TrieNode = node;
  126. let child: Map<string, TrieNode<Meta>> = node[2];
  127. const onToken = (token: string) => {
  128. // if (token === '') {
  129. // return true;
  130. // }
  131. parent = node;
  132. child = node[2];
  133. if (child.has(token)) {
  134. node = child.get(token)!;
  135. } else {
  136. return null;
  137. }
  138. onLoop(node, parent, token);
  139. return false;
  140. };
  141. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex) === null) {
  142. return null;
  143. }
  144. return { node, parent };
  145. };
  146. public contains(suffix: string, includeAllSubdomain = suffix[0] === '.'): boolean {
  147. const hostnameFromIndex = suffix[0] === '.' ? 1 : 0;
  148. const res = this.walkIntoLeafWithSuffix(suffix, hostnameFromIndex);
  149. if (!res) return false;
  150. if (includeAllSubdomain) return getBit(res.node[0], INCLUDE_ALL_SUBDOMAIN);
  151. return true;
  152. };
  153. private static bfsResults: [node: TrieNode | null, suffix: string[]] = [null, []];
  154. private static bfs<Meta>(this: void, nodeStack: FIFO<TrieNode<Meta>>, suffixStack: FIFO<string[]>) {
  155. const node = nodeStack.shift()!;
  156. const suffix = suffixStack.shift()!;
  157. node[2].forEach((childNode, k) => {
  158. // Pushing the child node to the stack for next iteration of DFS
  159. nodeStack.push(childNode);
  160. suffixStack.push([k, ...suffix]);
  161. });
  162. Triebase.bfsResults[0] = node;
  163. Triebase.bfsResults[1] = suffix;
  164. return Triebase.bfsResults;
  165. }
  166. private static bfsWithSort<Meta>(this: void, nodeStack: FIFO<TrieNode<Meta>>, suffixStack: FIFO<string[]>) {
  167. const node = nodeStack.shift()!;
  168. const suffix = suffixStack.shift()!;
  169. const child = node[2];
  170. if (child.size) {
  171. const keys = Array.from(child.keys()).sort(Triebase.compare);
  172. for (let i = 0, l = keys.length; i < l; i++) {
  173. const key = keys[i];
  174. const childNode = child.get(key)!;
  175. // Pushing the child node to the stack for next iteration of DFS
  176. nodeStack.push(childNode);
  177. suffixStack.push([key, ...suffix]);
  178. }
  179. }
  180. Triebase.bfsResults[0] = node;
  181. Triebase.bfsResults[1] = suffix;
  182. return Triebase.bfsResults;
  183. }
  184. private walk(
  185. onMatches: (suffix: string[], subdomain: boolean, meta: Meta) => void,
  186. initialNode = this.$root,
  187. initialSuffix: string[] = [],
  188. withSort = false
  189. ) {
  190. const bfsImpl = withSort ? Triebase.bfsWithSort : Triebase.bfs;
  191. const nodeStack = new FIFO<TrieNode<Meta>>();
  192. nodeStack.push(initialNode);
  193. // Resolving initial string (begin the start of the stack)
  194. const suffixStack = new FIFO<string[]>();
  195. suffixStack.push(initialSuffix);
  196. let node: TrieNode<Meta> = initialNode;
  197. let r;
  198. do {
  199. r = bfsImpl(nodeStack, suffixStack);
  200. node = r[0]!;
  201. const suffix = r[1];
  202. // If the node is a sentinel, we push the suffix to the results
  203. if (getBit(node[0], START)) {
  204. onMatches(suffix, getBit(node[0], INCLUDE_ALL_SUBDOMAIN), node[3]);
  205. }
  206. } while (nodeStack.length);
  207. };
  208. static compare(this: void, a: string, b: string) {
  209. if (a === b) return 0;
  210. return (a.length - b.length) || fastStringCompare(a, b);
  211. }
  212. private walkWithSort(
  213. onMatches: (suffix: string[], subdomain: boolean, meta: Meta) => void,
  214. initialNode = this.$root,
  215. initialSuffix: string[] = []
  216. ) {
  217. const nodeStack = new FIFO<TrieNode<Meta>>();
  218. nodeStack.push(initialNode);
  219. // Resolving initial string (begin the start of the stack)
  220. const suffixStack = new FIFO<string[]>();
  221. suffixStack.push(initialSuffix);
  222. let node: TrieNode<Meta> = initialNode;
  223. let child: Map<string, TrieNode<Meta>> = node[2];
  224. do {
  225. node = nodeStack.shift()!;
  226. const suffix = suffixStack.shift()!;
  227. child = node[2];
  228. if (child.size) {
  229. const keys = Array.from(child.keys()).sort(Triebase.compare);
  230. for (let i = 0, l = keys.length; i < l; i++) {
  231. const key = keys[i];
  232. const childNode = child.get(key)!;
  233. // Pushing the child node to the stack for next iteration of DFS
  234. nodeStack.push(childNode);
  235. suffixStack.push([key, ...suffix]);
  236. }
  237. }
  238. // If the node is a sentinel, we push the suffix to the results
  239. if (getBit(node[0], START)) {
  240. onMatches(suffix, getBit(node[0], INCLUDE_ALL_SUBDOMAIN), node[3]);
  241. }
  242. } while (nodeStack.length);
  243. };
  244. protected getSingleChildLeaf(tokens: string[]): FindSingleChildLeafResult<Meta> | null {
  245. let toPrune: TrieNode | null = null;
  246. let tokenToPrune: string | null = null;
  247. const onLoop = (node: TrieNode, parent: TrieNode, token: string) => {
  248. // Keeping track of a potential branch to prune
  249. const child = node[2];
  250. // console.log({
  251. // child, parent, token
  252. // });
  253. // console.log(this.inspect(0));
  254. if (toPrune !== null) { // the most near branch that could potentially being pruned
  255. if (child.size > 1) {
  256. // The branch has some children, the branch need retain.
  257. // And we need to abort prune that parent branch, so we set it to null
  258. toPrune = null;
  259. tokenToPrune = null;
  260. }
  261. } else if (child.size < 1) {
  262. // There is only one token child, or no child at all, we can prune it safely
  263. // It is now the top-est branch that could potentially being pruned
  264. toPrune = parent;
  265. tokenToPrune = token;
  266. }
  267. };
  268. const res = this.walkIntoLeafWithTokens(tokens, onLoop);
  269. if (res === null) return null;
  270. return { node: res.node, toPrune, tokenToPrune, parent: res.parent };
  271. };
  272. /**
  273. * Method used to retrieve every item in the trie with the given prefix.
  274. */
  275. public find(
  276. inputSuffix: string,
  277. subdomainOnly = inputSuffix[0] === '.',
  278. hostnameFromIndex = inputSuffix[0] === '.' ? 1 : 0
  279. // /** @default true */ includeEqualWithSuffix = true
  280. ): string[] {
  281. const inputTokens = hostnameToTokens(inputSuffix, hostnameFromIndex);
  282. const res = this.walkIntoLeafWithTokens(inputTokens);
  283. if (res === null) return [];
  284. const results: string[] = [];
  285. const onMatches = subdomainOnly
  286. ? (suffix: string[], subdomain: boolean) => { // fast path (default option)
  287. const d = fastStringArrayJoin(suffix, '.');
  288. if (!subdomain && subStringEqual(inputSuffix, d, 1)) return;
  289. results.push(subdomain ? '.' + d : d);
  290. }
  291. : (suffix: string[], subdomain: boolean) => { // fast path (default option)
  292. const d = fastStringArrayJoin(suffix, '.');
  293. results.push(subdomain ? '.' + d : d);
  294. };
  295. this.walk(
  296. onMatches,
  297. res.node, // Performing DFS from prefix
  298. inputTokens
  299. );
  300. return results;
  301. };
  302. /**
  303. * Method used to delete a prefix from the trie.
  304. */
  305. public remove(suffix: string): boolean {
  306. const res = this.getSingleChildLeaf(hostnameToTokens(suffix, 0));
  307. if (res === null) return false;
  308. if (missingBit(res.node[0], START)) return false;
  309. this.$size--;
  310. const { node, toPrune, tokenToPrune } = res;
  311. if (tokenToPrune && toPrune) {
  312. toPrune[2].delete(tokenToPrune);
  313. } else {
  314. node[0] = deleteBit(node[0], START);
  315. }
  316. return true;
  317. };
  318. // eslint-disable-next-line @typescript-eslint/unbound-method -- safe
  319. public delete = this.remove;
  320. /**
  321. * Method used to assert whether the given prefix exists in the Trie.
  322. */
  323. public has(suffix: string, includeAllSubdomain = suffix[0] === '.'): boolean {
  324. const hostnameFromIndex = suffix[0] === '.' ? 1 : 0;
  325. const res = this.walkIntoLeafWithSuffix(suffix, hostnameFromIndex);
  326. if (res === null) return false;
  327. if (missingBit(res.node[0], START)) return false;
  328. if (includeAllSubdomain) return getBit(res.node[0], INCLUDE_ALL_SUBDOMAIN);
  329. return true;
  330. };
  331. public dumpWithoutDot(onSuffix: (suffix: string, subdomain: boolean) => void, withSort = false) {
  332. const handleSuffix = (suffix: string[], subdomain: boolean) => {
  333. onSuffix(fastStringArrayJoin(suffix, '.'), subdomain);
  334. };
  335. if (withSort) {
  336. this.walkWithSort(handleSuffix);
  337. } else {
  338. this.walk(handleSuffix);
  339. }
  340. }
  341. public dump(onSuffix: (suffix: string) => void, withSort?: boolean): void;
  342. public dump(onSuffix?: null, withSort?: boolean): string[];
  343. public dump(onSuffix?: ((suffix: string) => void) | null, withSort = false): string[] | void {
  344. const results: string[] = [];
  345. const handleSuffix = onSuffix
  346. ? (suffix: string[], subdomain: boolean) => {
  347. const d = fastStringArrayJoin(suffix, '.');
  348. onSuffix(subdomain ? '.' + d : d);
  349. }
  350. : (suffix: string[], subdomain: boolean) => {
  351. const d = fastStringArrayJoin(suffix, '.');
  352. results.push(subdomain ? '.' + d : d);
  353. };
  354. if (withSort) {
  355. this.walkWithSort(handleSuffix);
  356. } else {
  357. this.walk(handleSuffix);
  358. }
  359. return results;
  360. };
  361. public dumpMeta(onMeta: (meta: Meta) => void, withSort?: boolean): void;
  362. public dumpMeta(onMeta?: null, withSort?: boolean): Meta[];
  363. public dumpMeta(onMeta?: ((meta: Meta) => void) | null, withSort = false): Meta[] | void {
  364. const results: Meta[] = [];
  365. const handleMeta = onMeta
  366. ? (_suffix: string[], _subdomain: boolean, meta: Meta) => onMeta(meta)
  367. : (_suffix: string[], _subdomain: boolean, meta: Meta) => results.push(meta);
  368. if (withSort) {
  369. this.walkWithSort(handleMeta);
  370. } else {
  371. this.walk(handleMeta);
  372. }
  373. return results;
  374. };
  375. public dumpWithMeta(onSuffix: (suffix: string, meta: Meta | undefined) => void, withSort?: boolean): void;
  376. public dumpWithMeta(onMeta?: null, withSort?: boolean): Array<[string, Meta | undefined]>;
  377. public dumpWithMeta(onSuffix?: ((suffix: string, meta: Meta | undefined) => void) | null, withSort = false): Array<[string, Meta | undefined]> | void {
  378. const results: Array<[string, Meta | undefined]> = [];
  379. const handleSuffix = onSuffix
  380. ? (suffix: string[], subdomain: boolean, meta: Meta | undefined) => {
  381. const d = fastStringArrayJoin(suffix, '.');
  382. return onSuffix(subdomain ? '.' + d : d, meta);
  383. }
  384. : (suffix: string[], subdomain: boolean, meta: Meta | undefined) => {
  385. const d = fastStringArrayJoin(suffix, '.');
  386. results.push([subdomain ? '.' + d : d, meta]);
  387. };
  388. if (withSort) {
  389. this.walkWithSort(handleSuffix);
  390. } else {
  391. this.walk(handleSuffix);
  392. }
  393. return results;
  394. };
  395. public inspect(depth: number, unpackMeta?: (meta?: Meta) => any) {
  396. return fastStringArrayJoin(
  397. JSON.stringify(deepTrieNodeToJSON(this.$root, unpackMeta), null, 2).split('\n').map((line) => ' '.repeat(depth) + line),
  398. '\n'
  399. );
  400. }
  401. public [util.inspect.custom](depth: number) {
  402. return this.inspect(depth);
  403. };
  404. public merge(trie: Triebase<Meta>) {
  405. const handleSuffix = (suffix: string[], subdomain: boolean, meta: Meta) => {
  406. this.add(fastStringArrayJoin(suffix, '.'), subdomain, meta);
  407. };
  408. trie.walk(handleSuffix);
  409. return this;
  410. }
  411. }
  412. export class HostnameSmolTrie<Meta = any> extends Triebase<Meta> {
  413. public smolTree = true;
  414. add(suffix: string, includeAllSubdomain = suffix[0] === '.', meta?: Meta, hostnameFromIndex = suffix[0] === '.' ? 1 : 0): void {
  415. let node: TrieNode<Meta> = this.$root;
  416. let curNodeChildren: Map<string, TrieNode<Meta>> = node[2];
  417. const onToken = (token: string) => {
  418. curNodeChildren = node[2];
  419. if (curNodeChildren.has(token)) {
  420. node = curNodeChildren.get(token)!;
  421. // During the adding of `[start]blog|.skk.moe` and find out that there is a `[start].skk.moe` in the trie, skip adding the rest of the node
  422. if (getBit(node[0], INCLUDE_ALL_SUBDOMAIN)) {
  423. return true;
  424. }
  425. } else {
  426. const newNode = createNode(node);
  427. curNodeChildren.set(token, newNode);
  428. node = newNode;
  429. }
  430. return false;
  431. };
  432. // When walkHostnameTokens returns true, we should skip the rest
  433. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex)) {
  434. return;
  435. }
  436. // If we are in smolTree mode, we need to do something at the end of the loop
  437. if (includeAllSubdomain) {
  438. // Trying to add `[.]sub.example.com` where there is already a `blog.sub.example.com` in the trie
  439. // Make sure parent `[start]sub.example.com` (without dot) is removed (SETINEL to false)
  440. // (/** parent */ node[2]!)[0] = false;
  441. // Removing the rest of the parent's child nodes
  442. node[2].clear();
  443. // The SENTINEL of this node will be set to true at the end of the function, so we don't need to set it here
  444. // we can use else-if here, because the children is now empty, we don't need to check the leading "."
  445. } else if (getBit(node[0], INCLUDE_ALL_SUBDOMAIN)) {
  446. // Trying to add `example.com` when there is already a `.example.com` in the trie
  447. // No need to increment size and set SENTINEL to true (skip this "new" item)
  448. return;
  449. }
  450. node[0] = setBit(node[0], START);
  451. if (includeAllSubdomain) {
  452. node[0] = setBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  453. } else {
  454. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  455. }
  456. node[3] = meta!;
  457. }
  458. public whitelist(suffix: string, includeAllSubdomain = suffix[0] === '.', hostnameFromIndex = suffix[0] === '.' ? 1 : 0) {
  459. const tokens = hostnameToTokens(suffix, hostnameFromIndex);
  460. const res = this.getSingleChildLeaf(tokens);
  461. if (res === null) return;
  462. const { node, toPrune, tokenToPrune } = res;
  463. // Trying to whitelist `[start].sub.example.com` where there might already be a `[start]blog.sub.example.com` in the trie
  464. if (includeAllSubdomain) {
  465. // If there is a `[start]sub.example.com` here, remove it
  466. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  467. node[0] = deleteBit(node[0], START);
  468. // Removing all the child nodes by empty the children
  469. node[2].clear();
  470. } else {
  471. // Trying to whitelist `example.com` when there is already a `.example.com` in the trie
  472. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  473. }
  474. // return early if not found
  475. if (missingBit(node[0], START)) return;
  476. if (toPrune && tokenToPrune) {
  477. toPrune[2].delete(tokenToPrune);
  478. } else {
  479. node[0] = deleteBit(node[0], START);
  480. }
  481. };
  482. }
  483. export class HostnameTrie<Meta = any> extends Triebase<Meta> {
  484. get size() {
  485. return this.$size;
  486. }
  487. add(suffix: string, includeAllSubdomain = suffix[0] === '.', meta?: Meta, hostnameFromIndex = suffix[0] === '.' ? 1 : 0): void {
  488. let node: TrieNode<Meta> = this.$root;
  489. let child: Map<string, TrieNode<Meta>> = node[2];
  490. const onToken = (token: string) => {
  491. child = node[2];
  492. if (child.has(token)) {
  493. node = child.get(token)!;
  494. } else {
  495. const newNode = createNode(node);
  496. child.set(token, newNode);
  497. node = newNode;
  498. }
  499. return false;
  500. };
  501. // When walkHostnameTokens returns true, we should skip the rest
  502. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex)) {
  503. return;
  504. }
  505. // if same entry has been added before, skip
  506. if (getBit(node[0], START)) {
  507. return;
  508. }
  509. this.$size++;
  510. node[0] = setBit(node[0], START);
  511. if (includeAllSubdomain) {
  512. node[0] = setBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  513. } else {
  514. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  515. }
  516. node[3] = meta!;
  517. }
  518. }
  519. // function deepEqualArray(a: string[], b: string[]) {
  520. // let len = a.length;
  521. // if (len !== b.length) return false;
  522. // while (len--) {
  523. // if (a[len] !== b[len]) return false;
  524. // }
  525. // return true;
  526. // };
  527. function subStringEqual(needle: string, haystack: string, needleIndex = 0) {
  528. for (let i = 0, l = haystack.length; i < l; i++) {
  529. if (needle[i + needleIndex] !== haystack[i]) return false;
  530. }
  531. return true;
  532. }