emqx_pqueue.erl 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. %% The contents of this file are subject to the Mozilla Public License
  2. %% Version 1.1 (the "License"); you may not use this file except in
  3. %% compliance with the License. You may obtain a copy of the License
  4. %% at http://www.mozilla.org/MPL/
  5. %%
  6. %% Software distributed under the License is distributed on an "AS IS"
  7. %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
  8. %% the License for the specific language governing rights and
  9. %% limitations under the License.
  10. %%
  11. %% The Original Code is RabbitMQ.
  12. %%
  13. %% The Initial Developer of the Original Code is GoPivotal, Inc.
  14. %% Copyright (c) 2007-2015 Pivotal Software, Inc. All rights reserved.
  15. %%
  16. %% Priority queues have essentially the same interface as ordinary
  17. %% queues, except that a) there is an in/3 that takes a priority, and
  18. %% b) we have only implemented the core API we need.
  19. %%
  20. %% Priorities should be integers - the higher the value the higher the
  21. %% priority - but we don't actually check that.
  22. %%
  23. %% in/2 inserts items with priority 0.
  24. %%
  25. %% We optimise the case where a priority queue is being used just like
  26. %% an ordinary queue. When that is the case we represent the priority
  27. %% queue as an ordinary queue. We could just call into the 'queue'
  28. %% module for that, but for efficiency we implement the relevant
  29. %% functions directly in here, thus saving on inter-module calls and
  30. %% eliminating a level of boxing.
  31. %%
  32. %% When the queue contains items with non-zero priorities, it is
  33. %% represented as a sorted kv list with the inverted Priority as the
  34. %% key and an ordinary queue as the value. Here again we use our own
  35. %% ordinary queue implemention for efficiency, often making recursive
  36. %% calls into the same function knowing that ordinary queues represent
  37. %% a base case.
  38. -module(emqx_pqueue).
  39. -export([ new/0
  40. , is_queue/1
  41. , is_empty/1
  42. , len/1
  43. , plen/2
  44. , to_list/1
  45. , from_list/1
  46. , in/2
  47. , in/3
  48. , out/1
  49. , out/2
  50. , out_p/1
  51. , join/2
  52. , filter/2
  53. , fold/3
  54. , highest/1
  55. ]).
  56. -export_type([q/0]).
  57. %%----------------------------------------------------------------------------
  58. -type(priority() :: integer() | 'infinity').
  59. -type(squeue() :: {queue, [any()], [any()], non_neg_integer()}).
  60. -type(pqueue() :: squeue() | {pqueue, [{priority(), squeue()}]}).
  61. -type(q() :: pqueue()).
  62. %%----------------------------------------------------------------------------
  63. -spec(new() -> pqueue()).
  64. new() ->
  65. {queue, [], [], 0}.
  66. -spec(is_queue(any()) -> boolean()).
  67. is_queue({queue, R, F, L}) when is_list(R), is_list(F), is_integer(L) ->
  68. true;
  69. is_queue({pqueue, Queues}) when is_list(Queues) ->
  70. lists:all(fun ({infinity, Q}) -> is_queue(Q);
  71. ({P, Q}) -> is_integer(P) andalso is_queue(Q)
  72. end, Queues);
  73. is_queue(_) ->
  74. false.
  75. -spec(is_empty(pqueue()) -> boolean()).
  76. is_empty({queue, [], [], 0}) ->
  77. true;
  78. is_empty(_) ->
  79. false.
  80. -spec(len(pqueue()) -> non_neg_integer()).
  81. len({queue, _R, _F, L}) ->
  82. L;
  83. len({pqueue, Queues}) ->
  84. lists:sum([len(Q) || {_, Q} <- Queues]).
  85. -spec(plen(priority(), pqueue()) -> non_neg_integer()).
  86. plen(0, {queue, _R, _F, L}) ->
  87. L;
  88. plen(_, {queue, _R, _F, _}) ->
  89. 0;
  90. plen(P, {pqueue, Queues}) ->
  91. case lists:keysearch(maybe_negate_priority(P), 1, Queues) of
  92. {value, {_, Q}} -> len(Q);
  93. false -> 0
  94. end.
  95. -spec(to_list(pqueue()) -> [{priority(), any()}]).
  96. to_list({queue, In, Out, _Len}) when is_list(In), is_list(Out) ->
  97. [{0, V} || V <- Out ++ lists:reverse(In, [])];
  98. to_list({pqueue, Queues}) ->
  99. [{maybe_negate_priority(P), V} || {P, Q} <- Queues,
  100. {0, V} <- to_list(Q)].
  101. -spec(from_list([{priority(), any()}]) -> pqueue()).
  102. from_list(L) ->
  103. lists:foldl(fun ({P, E}, Q) -> in(E, P, Q) end, new(), L).
  104. -spec(in(any(), pqueue()) -> pqueue()).
  105. in(Item, Q) ->
  106. in(Item, 0, Q).
  107. -spec(in(any(), priority(), pqueue()) -> pqueue()).
  108. in(X, 0, {queue, [_] = In, [], 1}) ->
  109. {queue, [X], In, 2};
  110. in(X, 0, {queue, In, Out, Len}) when is_list(In), is_list(Out) ->
  111. {queue, [X|In], Out, Len + 1};
  112. in(X, Priority, _Q = {queue, [], [], 0}) ->
  113. in(X, Priority, {pqueue, []});
  114. in(X, Priority, Q = {queue, _, _, _}) ->
  115. in(X, Priority, {pqueue, [{0, Q}]});
  116. in(X, Priority, {pqueue, Queues}) ->
  117. P = maybe_negate_priority(Priority),
  118. {pqueue, case lists:keysearch(P, 1, Queues) of
  119. {value, {_, Q}} ->
  120. lists:keyreplace(P, 1, Queues, {P, in(X, Q)});
  121. false when P == infinity ->
  122. [{P, {queue, [X], [], 1}} | Queues];
  123. false ->
  124. case Queues of
  125. [{infinity, InfQueue} | Queues1] ->
  126. [{infinity, InfQueue} |
  127. lists:keysort(1, [{P, {queue, [X], [], 1}} | Queues1])];
  128. _ ->
  129. lists:keysort(1, [{P, {queue, [X], [], 1}} | Queues])
  130. end
  131. end}.
  132. -spec(out(pqueue()) -> {empty | {value, any()}, pqueue()}).
  133. out({queue, [], [], 0} = Q) ->
  134. {empty, Q};
  135. out({queue, [V], [], 1}) ->
  136. {{value, V}, {queue, [], [], 0}};
  137. out({queue, [Y|In], [], Len}) ->
  138. [V|Out] = lists:reverse(In, []),
  139. {{value, V}, {queue, [Y], Out, Len - 1}};
  140. out({queue, In, [V], Len}) when is_list(In) ->
  141. {{value,V}, r2f(In, Len - 1)};
  142. out({queue, In,[V|Out], Len}) when is_list(In) ->
  143. {{value, V}, {queue, In, Out, Len - 1}};
  144. out({pqueue, [{P, Q} | Queues]}) ->
  145. {R, Q1} = out(Q),
  146. NewQ = case is_empty(Q1) of
  147. true -> case Queues of
  148. [] -> {queue, [], [], 0};
  149. [{0, OnlyQ}] -> OnlyQ;
  150. [_|_] -> {pqueue, Queues}
  151. end;
  152. false -> {pqueue, [{P, Q1} | Queues]}
  153. end,
  154. {R, NewQ}.
  155. -spec(out_p(pqueue()) -> {empty | {value, any(), priority()}, pqueue()}).
  156. out_p({queue, _, _, _} = Q) -> add_p(out(Q), 0);
  157. out_p({pqueue, [{P, _} | _]} = Q) -> add_p(out(Q), maybe_negate_priority(P)).
  158. out(0, {queue, _, _, _} = Q) ->
  159. out(Q);
  160. out(Priority, {queue, _, _, _}) ->
  161. erlang:error(badarg, [Priority]);
  162. out(Priority, {pqueue, Queues}) ->
  163. P = maybe_negate_priority(Priority),
  164. case lists:keysearch(P, 1, Queues) of
  165. {value, {_, Q}} ->
  166. {R, Q1} = out(Q),
  167. Queues1 = case is_empty(Q1) of
  168. true -> lists:keydelete(P, 1, Queues);
  169. false -> lists:keyreplace(P, 1, Queues, {P, Q1})
  170. end,
  171. {R, case Queues1 of
  172. [] -> {queue, [], [], 0};
  173. [{0, OnlyQ}] -> OnlyQ;
  174. [_|_] -> {pqueue, Queues1}
  175. end};
  176. false ->
  177. {empty, {pqueue, Queues}}
  178. end.
  179. add_p(R, P) -> case R of
  180. {empty, Q} -> {empty, Q};
  181. {{value, V}, Q} -> {{value, V, P}, Q}
  182. end.
  183. -spec(join(pqueue(), pqueue()) -> pqueue()).
  184. join(A, {queue, [], [], 0}) ->
  185. A;
  186. join({queue, [], [], 0}, B) ->
  187. B;
  188. join({queue, AIn, AOut, ALen}, {queue, BIn, BOut, BLen}) ->
  189. {queue, BIn, AOut ++ lists:reverse(AIn, BOut), ALen + BLen};
  190. join(A = {queue, _, _, _}, {pqueue, BPQ}) ->
  191. {Pre, Post} =
  192. lists:splitwith(fun ({P, _}) -> P < 0 orelse P == infinity end, BPQ),
  193. Post1 = case Post of
  194. [] -> [ {0, A} ];
  195. [ {0, ZeroQueue} | Rest ] -> [ {0, join(A, ZeroQueue)} | Rest ];
  196. _ -> [ {0, A} | Post ]
  197. end,
  198. {pqueue, Pre ++ Post1};
  199. join({pqueue, APQ}, B = {queue, _, _, _}) ->
  200. {Pre, Post} =
  201. lists:splitwith(fun ({P, _}) -> P < 0 orelse P == infinity end, APQ),
  202. Post1 = case Post of
  203. [] -> [ {0, B} ];
  204. [ {0, ZeroQueue} | Rest ] -> [ {0, join(ZeroQueue, B)} | Rest ];
  205. _ -> [ {0, B} | Post ]
  206. end,
  207. {pqueue, Pre ++ Post1};
  208. join({pqueue, APQ}, {pqueue, BPQ}) ->
  209. {pqueue, merge(APQ, BPQ, [])}.
  210. merge([], BPQ, Acc) ->
  211. lists:reverse(Acc, BPQ);
  212. merge(APQ, [], Acc) ->
  213. lists:reverse(Acc, APQ);
  214. merge([{P, A}|As], [{P, B}|Bs], Acc) ->
  215. merge(As, Bs, [ {P, join(A, B)} | Acc ]);
  216. merge([{PA, A}|As], Bs = [{PB, _}|_], Acc) when PA < PB orelse PA == infinity ->
  217. merge(As, Bs, [ {PA, A} | Acc ]);
  218. merge(As = [{_, _}|_], [{PB, B}|Bs], Acc) ->
  219. merge(As, Bs, [ {PB, B} | Acc ]).
  220. -spec(filter(fun ((any()) -> boolean()), pqueue()) -> pqueue()).
  221. filter(Pred, Q) -> fold(fun(V, P, Acc) ->
  222. case Pred(V) of
  223. true -> in(V, P, Acc);
  224. false -> Acc
  225. end
  226. end, new(), Q).
  227. -spec(fold(fun ((any(), priority(), A) -> A), A, pqueue()) -> A).
  228. fold(Fun, Init, Q) -> case out_p(Q) of
  229. {empty, _Q} -> Init;
  230. {{value, V, P}, Q1} -> fold(Fun, Fun(V, P, Init), Q1)
  231. end.
  232. -spec(highest(pqueue()) -> priority() | 'empty').
  233. highest({queue, [], [], 0}) -> empty;
  234. highest({queue, _, _, _}) -> 0;
  235. highest({pqueue, [{P, _} | _]}) -> maybe_negate_priority(P).
  236. r2f([], 0) -> {queue, [], [], 0};
  237. r2f([_] = R, 1) -> {queue, [], R, 1};
  238. r2f([X,Y], 2) -> {queue, [X], [Y], 2};
  239. r2f([X,Y|R], L) -> {queue, [X,Y], lists:reverse(R, []), L}.
  240. maybe_negate_priority(infinity) -> infinity;
  241. maybe_negate_priority(P) -> -P.