Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir parse binary data?

Tags:

erlang

elixir

​for example:

I have a binary look like this:

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

or

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

and so on...

The format is

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

I want parse binary get

  ["ok", "bcd"]

how to implement in Elixir or Erlang ?

Go version

a Go version parse this

func (c *Client) parse() []string {
    resp := []string{}
    buf := c.recv_buf.Bytes()
    var idx, offset int
    idx = 0
    offset = 0

    for {
        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 {
                continue
            } else {
                c.recv_buf.Next(offset)
                return resp
            }
        }

        size, err := strconv.Atoi(string(p))
        if err != nil || size < 0 {
            return nil
        }
        if offset+size >= c.recv_buf.Len() {
            break
        }

        v := buf[offset : offset+size]
        resp = append(resp, string(v))
        offset += size + 1
    }

    return []string{}
}

Thanks

like image 356
lidashuang Avatar asked Dec 14 '22 21:12

lidashuang


1 Answers

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]) do
  byte_size_int = byte_size |> String.to_integer
  <<parsed :: binary-size(byte_size_int)>> = bytes
  parsed
end
like image 197
bitwalker Avatar answered Dec 21 '22 03:12

bitwalker