small medium large xlarge

Generic-user-small
23 Mar 2016, 08:12
Dr. Franck PORCHER (1 post)

mp3_sync.erl (PDF §7 “The Bit Syntax”, page 106) is a great example at illustrating Erlang’s bit syntax.

However, the function mp3_sync:find_sync(), as written, lacks flexibility (what if you want to sync with more than 3 consecutive header frames) and is dangerously prone to error due to significant code redundancy.

The following version is both shorter, more flexible, and lacks code redundancy.


%% For standard sync (defaults to 3 consecutive headers), call find_bin/1 : find_bin(Bin)
find_sync(Bin) -> find_sync(Bin, 3). 

%% For another number of consecutive headers, call find_bin/2 : find_bin(Bin, NSync)
find_sync(Bin, NSync) -> find_sync(Bin, 1, 0, 0, NSync).

%% The engine : more flexible, no more dangerous code redundancy ;)
find_sync(   _, N,      _, S, NSync) -> {ok, N};
find_sync( Bin, N, Offset, S, NSync) ->  
    case is_header(N + Offset, Bin) of
        {ok, Len, _} -> find_sync(Bin,   N, Offset+Len, S+1, NSync);
               error -> find_sync(Bin, N+1,          0,   0, NSync) 
    end.

Cheers

You must be logged in to comment