1
+ type drop_priority = Newest | Oldest
2
+
1
3
module Locking = struct
2
4
type 'a t = {
3
5
mutex : Mutex .t ;
@@ -64,6 +66,26 @@ module Locking = struct
64
66
)
65
67
)
66
68
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
+
67
89
let take t =
68
90
Mutex. lock t.mutex;
69
91
match Queue. take_opt t.items with
@@ -101,6 +123,8 @@ module Locking = struct
101
123
let len = Queue. length t.items in
102
124
Mutex. unlock t.mutex;
103
125
len
126
+
127
+ let capacity t = t.capacity
104
128
105
129
let dump f t =
106
130
Fmt. pf f " <Locking stream: %d/%d items>" (length t) t.capacity
@@ -123,6 +147,11 @@ let take = function
123
147
| Sync x -> Sync. take x |> Result. get_ok (* todo: allow closing streams *)
124
148
| Locking x -> Locking. take x
125
149
150
+ let add_nonblocking ~drop_priority t v =
151
+ match t with
152
+ | Sync x -> if Sync. put_nonblocking x v then None else (Some v)
153
+ | Locking x -> Locking. add_nonblocking ~drop_priority x v
154
+
126
155
let take_nonblocking = function
127
156
| Locking x -> Locking. take_nonblocking x
128
157
| Sync x ->
@@ -134,8 +163,14 @@ let length = function
134
163
| Sync _ -> 0
135
164
| Locking x -> Locking. length x
136
165
166
+ let capacity = function
167
+ | Sync _ -> 0
168
+ | Locking x -> Locking. capacity x
169
+
137
170
let is_empty t = (length t = 0 )
138
171
172
+ let is_full t = (length t = capacity t)
173
+
139
174
let dump f = function
140
175
| Sync x -> Sync. dump f x
141
176
| Locking x -> Locking. dump f x
0 commit comments