Last active
September 21, 2024 17:14
-
-
Save feelfreetofee/a076c0385e4a4ea88eb8e650aa641956 to your computer and use it in GitHub Desktop.
Bencode module inspired on https://github.com/webtorrent/node-bencode
This file contains hidden or 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
| const types = { | |
| 100(data, position) { // d | |
| position[0]++ | |
| const dictionary = {} | |
| while (data[position[0]] !== 101) dictionary[buffer(data, position)] = decode(data, position) | |
| position[0]++ | |
| return dictionary | |
| }, | |
| 108(data, position) { // l | |
| position[0]++ | |
| const list = [] | |
| while (data[position[0]] !== 101) list.push(decode(data, position)) | |
| position[0]++ | |
| return list | |
| }, | |
| 105: (data, position) => parseInt(data.toString('ascii', position[0] + 1, (position[0] = data.indexOf(101, position[0]) + 1) - 1)) // i | |
| } | |
| const buffer = (data, position, sep) => data.slice(sep = data.indexOf(58, position[0]) + 1, position[0] = sep + parseInt(data.toString(undefined, position[0], sep - 1))) | |
| export const decode = (data, position = [0]) => data[position[0]] in types ? types[data[position[0]]]?.(data, position) : buffer(data, position).toString('ascii') | |
| export function encode(data) { | |
| const type = typeof data | |
| if (type === 'string') | |
| return (data.length + (encodeURIComponent(data).match(/%[89ABab]/g)?.length || 0)) + ':' + data | |
| else if (type === 'number') | |
| return 'i' + data + 'e' | |
| let buffer = data instanceof Array ? 'l' : 'd' | |
| if (buffer == 'l') | |
| for (const value of data) | |
| buffer += encode(value) | |
| else | |
| for (const key of Object.keys(data).sort()) | |
| buffer += encode(key) + encode(data[key]) | |
| return buffer + 'e' | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some benchmarks:
Code: