Last active
June 13, 2018 14:22
-
-
Save kimushu/3d86ebee3a10fb111821 to your computer and use it in GitHub Desktop.
Binary data operations by JavaScript TypedArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Find a character from memory block | |
* @param {Uint8Array} s Array to find | |
* @param {Number} c Character to find | |
* @param {Number} n Length of array in bytes | |
* @return Zero-based index (if not found, returns -1) | |
*/ | |
function memchr(s, c, n) { | |
return s.indexOf(c); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copy memory block | |
* @param {Uint8Array} dest Destination | |
* @param {Uint8Array} src Source | |
* @param {Number} n Length in bytes | |
*/ | |
function memcpy(dest, src, n) { | |
dest.set(src.slice(0, n)) | |
} | |
/** | |
* Copy memory block with offsets | |
* @param {Uint8Array} dest Destination | |
* @param {Number} destOffset Offset bytes for destination | |
* @param {Uint8Array} src Source | |
* @param {Number} srcOffset Offset bytes for source | |
* @param {Number} n Length in bytes | |
*/ | |
function memcpy_offseted(dest, destOffset, src, srcOffset, n) { | |
dest.set(src.slice(srcOffset, srcOffset + n), destOffset) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Find substring from memory block | |
* @param {Uint8Array} haystack Array to find | |
* @param {Number} haystacklen Length of haystack | |
* @param {Uint8Array} needle Array of substring | |
* @param {Number} needlelen Length of needle | |
* @return Zero-based index (if not found, returns -1) | |
*/ | |
function memmem(haystack, haystacklen, needle, needlelen) { | |
/* This algorithm may be SLOW */ | |
var next = 0; | |
while (next <= (haystacklen - needlelen)) { | |
var index = haystack.indexOf(needle[0], next); | |
if (index == -1) { | |
return -1; | |
} | |
var offset; | |
var found = 1; | |
for (offset = 1; offset < needlelen; ++offset) { | |
if (haystack[index + offset] != needle[offset]) { | |
found = 0; | |
break; | |
} | |
} | |
if (found) { | |
return index; | |
} | |
next = index + 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment