1 /* 2 * Copyright 2009-2012, 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, "%02" B_PRId64 ":%02d:%02d:%06d", 69 decomposed.hours, decomposed.minutes, decomposed.seconds, 70 decomposed.micros); 71 return buffer; 72 } 73 74 75 static inline BString 76 format_bigtime(bigtime_t time) 77 { 78 char buffer[64]; 79 format_bigtime(time, buffer, sizeof(buffer)); 80 return BString(buffer); 81 } 82 83 84 static inline const char* 85 format_nanotime(nanotime_t time, char* buffer, size_t bufferSize) 86 { 87 decomposed_nanotime decomposed; 88 decompose_time(time, decomposed); 89 90 snprintf(buffer, bufferSize, "%02" B_PRId64 ":%02d:%02d:%09d", 91 decomposed.hours, decomposed.minutes, decomposed.seconds, 92 decomposed.nanos); 93 return buffer; 94 } 95 96 97 static inline BString 98 format_nanotime(nanotime_t time) 99 { 100 char buffer[64]; 101 format_nanotime(time, buffer, sizeof(buffer)); 102 return BString(buffer); 103 } 104 105 106 #endif // TIME_UTILS_H 107