summaryrefslogtreecommitdiff
path: root/bytes/bytes.ts
diff options
context:
space:
mode:
authorYusuke Sakurai <kerokerokerop@gmail.com>2019-02-11 08:49:48 +0900
committerRyan Dahl <ry@tinyclouds.org>2019-02-10 18:49:48 -0500
commit33f62789cde407059abba0a7ac18b2145c648ea7 (patch)
tree454d487f232a61f6c57e2ebdad66e49bf939e4d6 /bytes/bytes.ts
parented20bda6ec324b8143c6210024647d2692232c26 (diff)
feat: multipart, etc.. (denoland/deno_std#180)
Original: https://github.com/denoland/deno_std/commit/fda9c98d055091fa886fa444ebd1adcd2ecd21bc
Diffstat (limited to 'bytes/bytes.ts')
-rw-r--r--bytes/bytes.ts60
1 files changed, 60 insertions, 0 deletions
diff --git a/bytes/bytes.ts b/bytes/bytes.ts
new file mode 100644
index 000000000..ef333288e
--- /dev/null
+++ b/bytes/bytes.ts
@@ -0,0 +1,60 @@
+// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
+
+/** Find first index of binary pattern from a. If not found, then return -1 **/
+export function bytesFindIndex(a: Uint8Array, pat: Uint8Array): number {
+ const s = pat[0];
+ for (let i = 0; i < a.length; i++) {
+ if (a[i] !== s) continue;
+ const pin = i;
+ let matched = 1;
+ while (matched < pat.length) {
+ i++;
+ if (a[i] !== pat[i - pin]) {
+ break;
+ }
+ matched++;
+ }
+ if (matched === pat.length) {
+ return pin;
+ }
+ }
+ return -1;
+}
+
+/** Find last index of binary pattern from a. If not found, then return -1 **/
+export function bytesFindLastIndex(a: Uint8Array, pat: Uint8Array) {
+ const e = pat[pat.length - 1];
+ for (let i = a.length - 1; i >= 0; i--) {
+ if (a[i] !== e) continue;
+ const pin = i;
+ let matched = 1;
+ while (matched < pat.length) {
+ i--;
+ if (a[i] !== pat[pat.length - 1 - (pin - i)]) {
+ break;
+ }
+ matched++;
+ }
+ if (matched === pat.length) {
+ return pin - pat.length + 1;
+ }
+ }
+ return -1;
+}
+
+/** Check whether binary arrays are equal to each other **/
+export function bytesEqual(a: Uint8Array, match: Uint8Array): boolean {
+ if (a.length !== match.length) return false;
+ for (let i = 0; i < match.length; i++) {
+ if (a[i] !== match[i]) return false;
+ }
+ return true;
+}
+
+/** Check whether binary array has binary prefix **/
+export function bytesHasPrefix(a: Uint8Array, prefix: Uint8Array): boolean {
+ for (let i = 0, max = prefix.length; i < max; i++) {
+ if (a[i] !== prefix[i]) return false;
+ }
+ return true;
+}