]>
git.ipfire.org Git - thirdparty/squid.git/blob - lib/util.c
639cc892a235e13bf66c35d3726471ae85fef057
2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
39 tvSubUsec(struct timeval t1
, struct timeval t2
)
41 return (t2
.tv_sec
- t1
.tv_sec
) * 1000000 +
42 (t2
.tv_usec
- t1
.tv_usec
);
46 tvSubDsec(struct timeval t1
, struct timeval t2
)
48 return (double) (t2
.tv_sec
- t1
.tv_sec
) +
49 (double) (t2
.tv_usec
- t1
.tv_usec
) / 1000000.0;
52 /* somewhat safer calculation of %s */
54 xpercent(double part
, double whole
)
56 return xdiv(100 * part
, whole
);
60 xpercentInt(double part
, double whole
)
63 return (int) rint(xpercent(part
, whole
));
65 /* SCO 3.2v4.2 doesn't have rint() -- mauri@mbp.ee */
66 return (int) floor(xpercent(part
, whole
) + 0.5);
70 /* somewhat safer division */
72 xdiv(double nom
, double denom
)
74 return (denom
!= 0.0) ? nom
/ denom
: -1.0;
77 /* integer to string */
81 static char buf
[24]; /* 2^64 = 18446744073709551616 */
82 snprintf(buf
, sizeof(buf
), "%d", num
);
86 /* int64_t to string */
88 xint64toa(int64_t num
)
90 static char buf
[24]; /* 2^64 = 18446744073709551616 */
91 snprintf(buf
, sizeof(buf
), "%" PRId64
, num
);
98 g
->gb
+= (g
->bytes
>> 30);
99 g
->bytes
&= (1 << 30) - 1;
103 gb_to_double(const gb_t
* g
)
105 return ((double) g
->gb
) * ((double) (1 << 30)) + ((double) g
->bytes
);
109 double_to_str(char *buf
, int buf_size
, double value
)
114 snprintf(buf
, buf_size
, "%.2f MB", value
/ 1e6
);
115 else if (value
< 1e12
)
116 snprintf(buf
, buf_size
, "%.3f GB", value
/ 1e9
);
118 snprintf(buf
, buf_size
, "%.4f TB", value
/ 1e12
);
124 gb_to_str(const gb_t
* g
)
127 * it is often convenient to call gb_to_str several times for _one_ printf
129 #define max_cc_calls 5
130 typedef char GbBuf
[32];
131 static GbBuf bufs
[max_cc_calls
];
132 static int call_id
= 0;
133 double value
= gb_to_double(g
);
134 char *buf
= bufs
[call_id
++];
136 if (call_id
>= max_cc_calls
)
141 snprintf(buf
, sizeof(GbBuf
), "%.2f MB", value
/ 1e6
);
142 else if (value
< 1e12
)
143 snprintf(buf
, sizeof(GbBuf
), "%.2f GB", value
/ 1e9
);
145 snprintf(buf
, sizeof(GbBuf
), "%.2f TB", value
/ 1e12
);
151 * rounds num to the next upper integer multiple of what
153 unsigned int RoundTo(const unsigned int num
, const unsigned int what
)
155 return what
* ((num
+ what
-1)/what
);