Remove dependency on ocaml-extlib
[virt-top.git] / src / utils.ml
1 (* 'top'-like tool for libvirt domains.
2    (C) Copyright 2007-2009 Richard W.M. Jones, Red Hat Inc.
3    http://libvirt.org/
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19    This file contains utility functions.
20 *)
21
22 open Printf
23
24 let (//) = Filename.concat
25
26 (* Int64 operators for convenience. *)
27 let (+^) = Int64.add
28 let (-^) = Int64.sub
29 let ( *^ ) = Int64.mul
30 let (/^) = Int64.div
31
32 (* failwithf is a printf-like version of failwith. *)
33 let failwithf fs = ksprintf failwith fs
34
35 let rec range a b =
36   if a <= b then
37     a :: range (a+1) b
38   else
39     []
40
41 (* Input a whole file as a list of lines. *)
42 let input_all_lines chan =
43   let lines = ref [] in
44   (try
45      while true; do
46        lines := input_line chan :: !lines
47      done
48    with
49      End_of_file -> ());
50   List.rev !lines
51
52 (* Trim whitespace from the beginning and end of strings. *)
53 let isspace c =
54   c = ' '
55   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
56
57 let triml ?(test = isspace) str =
58   let i = ref 0 in
59   let n = ref (String.length str) in
60   while !n > 0 && test str.[!i]; do
61     decr n;
62     incr i
63   done;
64   if !i = 0 then str
65   else String.sub str !i !n
66
67 let trimr ?(test = isspace) str =
68   let n = ref (String.length str) in
69   while !n > 0 && test str.[!n-1]; do
70     decr n
71   done;
72   if !n = String.length str then str
73   else String.sub str 0 !n
74
75 let trim ?(test = isspace) str =
76   trimr (triml str)
77
78 (* Split string on the first instance of 'sep' character. *)
79 let split str sep =
80   try
81     let i = String.index str sep in
82     String.sub str 0 i, String.sub str (i+1) (String.length str - 1)
83   with
84     Not_found -> str, ""
85
86 (* Read a configuration file as a list of (key, value) pairs.
87  * If the config file is missing this returns an empty list.
88  *)
89 let blanks_and_comments = Str.regexp "^[ \t]*\\(#.*\\)?$"
90
91 let read_config_file filename =
92   let lines =
93     try
94       let chan = open_in filename in
95       let lines = input_all_lines chan in
96       close_in chan;
97       lines
98     with
99       Sys_error _ -> [] in           (* Ignore errors opening file. *)
100
101   (* Line numbers. *)
102   let lines =
103     let i = ref 0 in List.map (fun line -> (incr i; !i), line) lines in
104
105   (* Remove blank lines and comment lines. *)
106   let lines =
107     List.filter
108       (fun (lineno, line) ->
109          not (Str.string_match blanks_and_comments line 0)) lines in
110
111   (* Convert to key, value pairs. *)
112   List.map (
113     fun (lineno, line) ->
114       let key, value = split line ' ' in
115       lineno, trim key, trim value
116   ) lines
117
118 (* Pad a string to the full width with spaces.  If too long, truncate. *)
119 let pad width str =
120   if width <= 0 then ""
121   else (
122     let n = String.length str in
123     if n = width then str
124     else if n > width then String.sub str 0 width
125     else (* if n < width then *) str ^ String.make (width-n) ' '
126   )
127
128 (* Take up to n elements of xs, if available. *)
129 let rec list_take n xs =
130   if n <= 0 then []
131   else (
132     match xs with
133     | [] -> []
134     | x :: xs -> x :: list_take (n-1) xs
135   )
136
137 let map_default f def = function
138   | None -> def
139   | Some v -> f v
140
141 module Show = struct
142   (* Show a percentage in 4 chars. *)
143   let percent percent =
144     if percent <= 0. then " 0.0"
145     else if percent <= 9.9 then sprintf " %1.1f" percent
146     else if percent <= 99.9 then sprintf "%2.1f" percent
147     else "100 "
148
149   (* Show an int64 option in 4 chars. *)
150   let rec int64_option = function
151     | None -> "    "
152     | Some n -> int64 n
153   (* Show an int64 in 4 chars. *)
154   and int64 = function
155     | n when n < 0L -> "-!!!"
156     | n when n <= 9999L ->
157         sprintf "%4Ld" n
158     | n when n /^ 1024L <= 999L ->
159         sprintf "%3LdK" (n /^ 1024L)
160     | n when n /^ 1_048_576L <= 999L ->
161         sprintf "%3LdM" (n /^ 1_048_576L)
162     | n when n /^ 1_073_741_824L <= 999L ->
163         sprintf "%3LdG" (n /^ 1_073_741_824L)
164     | _ -> ">!!!"
165
166   (* Format the total time (may be large!) in 9 chars. *)
167   let time ns =
168     let secs_in_ns = 1_000_000_000L in
169     let mins_in_ns = 60_000_000_000L in
170     let hours_in_ns = 3_600_000_000_000L in
171
172     let hours = ns /^ hours_in_ns in
173     let ns = ns -^ (hours *^ hours_in_ns) in
174     let mins = ns /^ mins_in_ns in
175     let ns = ns -^ (mins *^ mins_in_ns) in
176     let secs = ns /^ secs_in_ns in
177     let ns = ns -^ (secs *^ secs_in_ns) in
178     let pennies = ns /^ 10_000_000L in
179
180     if hours < 12L then
181       sprintf "%3Ld:%02Ld.%02Ld" (hours *^ 60L +^ mins) secs pennies
182     else if hours <= 999L then
183       sprintf "%3Ld:%02Ld:%02Ld" hours mins secs
184     else (
185       let days = hours /^ 24L in
186       let hours = hours -^ (days *^ 24L) in
187       sprintf "%3Ldd%02Ld:%02Ld" days hours mins
188     )
189 end