package batteries

  1. Overview
  2. Docs
A community-maintained standard library extension

Install

dune-project
 Dependency

Authors

Maintainers

Sources

batteries-3.10.0.tar.gz
md5=b7f3b99f12f21b1da6b6aa13d993206d
sha512=8b7f2479eb0271bcfd9168887c1e4a9a815c512eab3ee61b150fc4dfa9ec803e4f73115155f20b3017e4a822148d0e6d1c1e8e5f96790fd691b419dd39a908a2

doc/src/batteries.unthreaded/batConcreteQueue.ml.html

Source file batConcreteQueue.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 1 "src/batConcreteQueue_403.ml"
[@@@warning "-37"]
(* Disable warning 37 (Unused constructor):
   Cons is never used to build values,
   but it is used implicitly in [of_abstr] *)
type 'a cell =
  | Nil
  | Cons of { content: 'a; mutable next: 'a cell }


type 'a t = {
  mutable length: int;
  mutable first: 'a cell;
  mutable last: 'a cell
}

external of_abstr : 'a Queue.t -> 'a t = "%identity"
external to_abstr : 'a t -> 'a Queue.t = "%identity"

let filter_inplace f queue =
  (* find_next returns the next 'true' cell, or Nil *)
  let rec find_next = function
    | Nil -> Nil
    | (Cons cell) as cons ->
       if f cell.content then cons
       else find_next cell.next
  in
  (* last is the last known 'true' Cons cell
     (may be Nil if no true cell has be found yet)
     next is the next candidate true cell
     (may be Nil if there is no next cell) *)
  let rec loop length last next = match next with
    | Nil -> (length, last)
    | (Cons cell) as cons ->
       let next = find_next cell.next in
       cell.next <- next;
       loop (length + 1) cons next
  in
  let first = find_next queue.first in
  (* returning a pair is unnecessary, the writes could be made at the
     end of 'loop', but the present style makes it obvious that all
     three writes are performed atomically, without allocation,
     function call or return (yield points) in between, guaranteeing
     some form of state consistency in the face of signals, threading
     or what not. *)
  let (length, last) = loop 0 Nil first in
  queue.length <- length;
  queue.first <- first;
  queue.last <- last;
  ()