add iot_queue

This commit is contained in:
anlicheng 2024-08-01 11:33:10 +08:00
parent 45f7560957
commit 5d0c4a0900

View File

@ -0,0 +1,45 @@
%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 01. 8 2024 11:17
%%%-------------------------------------------------------------------
-module(iot_queue).
-author("anlicheng").
%% API
-export([new/1, in/2, out/1]).
-record(iot_queue, {
capacity = 1024,
len = 0,
queue = queue:new() :: queue:queue()
}).
-spec new(Capacity :: integer()) -> Q :: #iot_queue{}.
new(Capacity) when is_integer(Capacity) ->
#iot_queue{
capacity = Capacity,
len = 0,
queue = queue:new()
}.
-spec in(Item :: any(), TQ :: #iot_queue{}) -> NQ :: #iot_queue{}.
in(_Item, TQ = #iot_queue{capacity = Capacity, len = Len}) when Len >= Capacity ->
TQ;
in(Item, TQ = #iot_queue{queue = Q, len = Len}) ->
TQ#iot_queue{
queue = queue:in(Item, Q),
len = Len + 1
}.
-spec out(TQ :: #iot_queue{}) -> {{value, Item :: any()}, TQ1 :: #iot_queue{}} | {empty, TQ1 :: #iot_queue{}}.
out(TQ = #iot_queue{queue = Q, len = Len}) ->
case queue:out(Q) of
{{value, Item}, Q1} ->
{{value, Item}, TQ#iot_queue{queue = Q1, len = Len - 1}};
{empty, _} ->
{empty, TQ}
end.