1+ type drop_priority = Newest | Oldest
2+
13module Locking = struct
24 type 'a t = {
35 mutex : Mutex .t ;
@@ -64,6 +66,26 @@ module Locking = struct
6466 )
6567 )
6668
69+ let add_nonblocking ~drop_priority t item =
70+ Mutex. lock t.mutex;
71+ match Waiters. wake_one t.readers item with
72+ | `Ok -> Mutex. unlock t.mutex; None
73+ | `Queue_empty ->
74+ (* No-one is waiting for an item. Queue it. *)
75+ if Queue. length t.items < t.capacity then (
76+ Queue. add item t.items;
77+ Mutex. unlock t.mutex;
78+ None
79+ ) else (
80+ match drop_priority with
81+ | Newest -> Mutex. unlock t.mutex; Some item
82+ | Oldest ->
83+ let dropped_item = Queue. take t.items in
84+ Queue. add item t.items;
85+ Mutex. unlock t.mutex;
86+ Some dropped_item
87+ )
88+
6789 let take t =
6890 Mutex. lock t.mutex;
6991 match Queue. take_opt t.items with
@@ -101,6 +123,8 @@ module Locking = struct
101123 let len = Queue. length t.items in
102124 Mutex. unlock t.mutex;
103125 len
126+
127+ let capacity t = t.capacity
104128
105129 let dump f t =
106130 Fmt. pf f " <Locking stream: %d/%d items>" (length t) t.capacity
@@ -123,6 +147,11 @@ let take = function
123147 | Sync x -> Sync. take x |> Result. get_ok (* todo: allow closing streams *)
124148 | Locking x -> Locking. take x
125149
150+ let add_nonblocking ~drop_priority t v =
151+ match t with
152+ | Sync _ -> Some v
153+ | Locking x -> Locking. add_nonblocking ~drop_priority x v
154+
126155let take_nonblocking = function
127156 | Locking x -> Locking. take_nonblocking x
128157 | Sync x ->
@@ -134,8 +163,14 @@ let length = function
134163 | Sync _ -> 0
135164 | Locking x -> Locking. length x
136165
166+ let capacity = function
167+ | Sync _ -> 0
168+ | Locking x -> Locking. capacity x
169+
137170let is_empty t = (length t = 0 )
138171
172+ let is_full t = (length t = capacity t)
173+
139174let dump f = function
140175 | Sync x -> Sync. dump f x
141176 | Locking x -> Locking. dump f x
0 commit comments