0
所以我寫了兩個版本的gen_fsm來解析一個字節流。我正在尋找一個以字符串snp
開頭的數據包,然後我想在p
之後保存下一個20個字節。這段代碼只關心查找標題。我需要一些建議,指出哪一種是更加慣用的Erlang或更好的寫法。哪一種比較習慣?
選項1
parse_header({parse, Byte}, {Header, [Next | Rest]}) ->
case Byte of
Next when length(Rest) > 0 -> {next_state, parse_header, {Header, Rest}};
Next when length(Rest) == 0 -> {next_state, parse_data, []};
$s -> parse_header({parse, Byte}, {Header, Header});
_ -> {next_state, parse_header, {Header, Header}}
end.
選項2
parse_start({parse, Byte}, State) when Byte == $s ->
{next_state, parse_new, State};
parse_start({parse, Byte}, State) when Byte /= $s ->
{next_state, parse_start, State}.
parse_new({parse, Byte}, State) when Byte == $n ->
{next_state, parse_packet, State};
parse_new({parse, Byte}, State) when Byte == $s ->
parse_start({parse, Byte}, State);
parse_new({parse, _Byte}, State) ->
{next_state, parse_start, State}.
parse_packet({parse, Byte}, State) when Byte == $p ->
{next_state, parse_data, State};
parse_packet({parse, Byte}, State) when Byte == $s ->
parse_start({parse, Byte}, State);
parse_packet({parse, _Byte}, State) ->
{next_state, parse_start, State}.