Last active
August 29, 2015 14:28
-
-
Save k-takata/37dd48139aff9dfdc4bd to your computer and use it in GitHub Desktop.
Test for new vimproc data handling routine
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
" Encode a 32-bit integer into a 5-byte string. | |
function! s:encode_size(n) | |
" Set each bit7 to 1 in order to avoid NUL byte. | |
return printf("%c%c%c%c%c", | |
\ ((a:n / 0x10000000) % 0x80) + 0x80, | |
\ ((a:n / 0x200000) % 0x80) + 0x80, | |
\ ((a:n / 0x4000) % 0x80) + 0x80, | |
\ ((a:n / 0x80) % 0x80) + 0x80, | |
\ ( a:n % 0x80) + 0x80) | |
endfunction | |
" Decode a 32-bit integer from a 5-byte string. | |
function! s:decode_size(str) | |
return | |
\ (char2nr(a:str[0]) - 0x80) * 0x10000000 + | |
\ (char2nr(a:str[1]) - 0x80) * 0x200000 + | |
\ (char2nr(a:str[2]) - 0x80) * 0x4000 + | |
\ (char2nr(a:str[3]) - 0x80) * 0x80 + | |
\ (char2nr(a:str[4]) - 0x80) | |
endfunction | |
" Encode a list into a string. | |
function! s:encode_list(arr) | |
" End Of Value | |
let EOV = "\xFF" | |
" encoded size0, data0, EOV, encoded size1, data1, EOV, ... | |
return empty(a:arr) ? '' : | |
\ (EOV . join(map(copy(a:arr), 's:encode_size(strlen(v:val)) . v:val'), EOV) . EOV) | |
endfunction | |
" Decode a list from a string. | |
function! s:decode_list(str) | |
let err = 0 | |
" End Of Value | |
let EOV = "\xFF" | |
if a:str[0] != EOV | |
let err = 1 | |
return [[a:str], err] | |
endif | |
let arr = [] | |
let str = a:str[1:] | |
while strlen(str) >= 5 | |
let size = s:decode_size(str) | |
let arr += [str[5 : 5 + size - 1]] | |
let str = str[5 + size + 1 :] | |
endwhile | |
return [arr, err] | |
endfunction | |
" test | |
let n = 123456789 | |
let res = s:encode_size(n) | |
echo res[0] res[1] res[2] res[3] res[4] | |
echo s:decode_size(res) | |
let arr = [1, "hoge", 3, "", "\n", 0] | |
let str = s:encode_list(arr) | |
echo "str: " str | |
echo s:decode_list(str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment