queue:split/2 unsafe!? => queue_split_at_most/2

Tuesday, 9th April, 2013

[updated after discussion on erlang-questions, starting here]

I’ve just discovered that queue:split(N, Queue) causes a crash if N is larger than Queue has items:


    1> self().
    <0.37.0>
    2> Q1 = queue:new().    
    {[],[]}
    3> Q2 = queue:in(a, Q1).
    {[a],[]}
    4> Q3 = queue:in(b, Q2).
    {[b],[a]}
    5> Q4 = queue:in(c, Q3).
    {[c,b],[a]}
    6> queue:split(4, Q4).  
    ** exception error: bad argument
         in function  queue:split/2
            called as queue:split(4,{[c,b],[a]})
    7> self().              
    <0.45.0>           
    

Here’s a safe split:


    queue_split_at_most(N, Q) ->
        case queue:len(Q) >= N of
            true ->
                queue:split(N,Q);
            false ->
                {Q, queue:new()}
        end.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: