xref: /haiku/src/apps/debuganalyzer/util/TimeUtils.h (revision 9760dcae2038d47442f4658c2575844c6cf92c40)
1 /*
2  * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de.
3  * Distributed under the terms of the MIT License.
4  */
5 #ifndef TIME_UTILS_H
6 #define TIME_UTILS_H
7 
8 
9 #include <stdio.h>
10 
11 
12 struct decomposed_bigtime {
13 	nanotime_t	hours;
14 	int			minutes;
15 	int			seconds;
16 	int			micros;
17 };
18 
19 
20 struct decomposed_nanotime {
21 	nanotime_t	hours;
22 	int			minutes;
23 	int			seconds;
24 	int			nanos;
25 };
26 
27 
28 static void
29 decompose_time(bigtime_t time, decomposed_bigtime& decomposed)
30 {
31 	// nanosecs
32 	decomposed.micros = time % 1000000;
33 	time /= 1000000;
34 	// secs
35 	decomposed.seconds = time % 60;
36 	time /= 60;
37 	// mins
38 	decomposed.minutes = time % 60;
39 	time /= 60;
40 	// hours
41 	decomposed.hours = time;
42 }
43 
44 
45 static void
46 decompose_time(nanotime_t time, decomposed_nanotime& decomposed)
47 {
48 	// nanosecs
49 	decomposed.nanos = time % 1000000000;
50 	time /= 1000000000;
51 	// secs
52 	decomposed.seconds = time % 60;
53 	time /= 60;
54 	// mins
55 	decomposed.minutes = time % 60;
56 	time /= 60;
57 	// hours
58 	decomposed.hours = time;
59 }
60 
61 
62 static inline const char*
63 format_bigtime(bigtime_t time, char* buffer, size_t bufferSize)
64 {
65 	decomposed_bigtime decomposed;
66 	decompose_time(time, decomposed);
67 
68 	snprintf(buffer, bufferSize, "%02lld:%02d:%02d:%06d", decomposed.hours,
69 		decomposed.minutes, decomposed.seconds, decomposed.micros);
70 	return buffer;
71 }
72 
73 
74 static inline BString
75 format_bigtime(bigtime_t time)
76 {
77 	char buffer[64];
78 	format_bigtime(time, buffer, sizeof(buffer));
79 	return BString(buffer);
80 }
81 
82 
83 static inline const char*
84 format_nanotime(nanotime_t time, char* buffer, size_t bufferSize)
85 {
86 	decomposed_nanotime decomposed;
87 	decompose_time(time, decomposed);
88 
89 	snprintf(buffer, bufferSize, "%02lld:%02d:%02d:%09d", decomposed.hours,
90 		decomposed.minutes, decomposed.seconds, decomposed.nanos);
91 	return buffer;
92 }
93 
94 
95 static inline BString
96 format_nanotime(nanotime_t time)
97 {
98 	char buffer[64];
99 	format_nanotime(time, buffer, sizeof(buffer));
100 	return BString(buffer);
101 }
102 
103 
104 #endif	// TIME_UTILS_H
105