Wednesday, 15 February 2012

erlang - Elixir parse binary data? -



erlang - Elixir parse binary data? -

​for example:

i have binary this:

bin1 = "2\nok\n3\nbcd\n\n"​

or

bin2 = "2\nok\n3\nbcd\n1\na\n\n"​

and on...

the format

byte_size \n bytes \n byte_size \n bytes \n \n

i want parse binary get

["ok", "bcd"]

how implement in elixir or erlang ?

go version

a golang version parse this

func (c *client) parse() []string { resp := []string{} buf := c.recv_buf.bytes() var idx, offset int idx = 0 offset = 0 { idx = bytes.indexbyte(buf[offset:], '\n') if idx == -1 { break } p := buf[offset : offset+idx] offset += idx + 1 //fmt.printf("> [%s]\n", p); if len(p) == 0 || (len(p) == 1 && p[0] == '\r') { if len(resp) == 0 { go on } else { c.recv_buf.next(offset) homecoming resp } } size, err := strconv.atoi(string(p)) if err != nil || size < 0 { homecoming nil } if offset+size >= c.recv_buf.len() { break } v := buf[offset : offset+size] resp = append(resp, string(v)) offset += size + 1 } homecoming []string{} }

thanks

a more flexible solution:

result = bin |> string.split("\n") |> stream.chunk(2) |> stream.map(&parse_bytes/1) |> enum.filter(fn s -> s != "" end) def parse_bytes(["", ""]), do: "" def parse_bytes([byte_size, bytes]) byte_size_int = byte_size |> string.to_integer <<parsed :: [binary, size(byte_size_int)]>> = bytes parsed end

erlang elixir

No comments:

Post a Comment