SequoiaDB
 All Classes Namespaces Files Functions Macros Pages
misc.h
1 /* @file misc.h
2 */
3 
4 /*
5  * Copyright 2009 10gen Inc.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 
20 #pragma once
21 
22 #include <ctime>
23 
24 namespace bson {
25 
26  using namespace std;
27 
28  inline void time_t_to_String(time_t t, char *buf) {
29 #if defined(_WIN32)
30  ctime_s(buf, 32, &t);
31 #else
32  ctime_r(&t, buf);
33 #endif
34  buf[ strlen( buf ) - 1 ] = 0; // don't want the \n
35  }
36 
37  inline string time_t_to_String(time_t t = time(0) ) {
38  char buf[64];
39 #if defined(_WIN32)
40  ctime_s(buf, sizeof(buf), &t);
41 #else
42  ctime_r(&t, buf);
43 #endif
44  buf[ strlen( buf ) - 1 ] = 0; // don't want the \n
45  return buf;
46  }
47 
48  inline string time_t_to_String_no_year(time_t t) {
49  char buf[64];
50 #if defined(_WIN32)
51  ctime_s(buf, sizeof(buf), &t);
52 #else
53  ctime_r(&t, buf);
54 #endif
55  buf[19] = 0;
56  return buf;
57  }
58 
59  inline string time_t_to_String_short(time_t t) {
60  char buf[64];
61 #if defined(_WIN32)
62  ctime_s(buf, sizeof(buf), &t);
63 #else
64  ctime_r(&t, buf);
65 #endif
66  buf[19] = 0;
67  if( buf[0] && buf[1] && buf[2] && buf[3] )
68  return buf + 4; // skip day of week
69  return buf;
70  }
71 
72  struct Date_t {
73  long long millis;
74  Date_t(): millis(0) {}
75  Date_t(long long m): millis(m) {}
76  operator long long&() { return millis; }
77  operator const long long&() const { return millis; }
78  string toString() const {
79  char buf[64];
80  time_t_to_String(millis/1000, buf);
81  return buf;
82  }
83  };
84 
85  // Like strlen, but only scans up to n bytes.
86  // Returns -1 if no '0' found.
87  inline int strnlen( const char *s, int n ) {
88  for( int i = 0; i < n; ++i )
89  if ( !s[ i ] )
90  return i;
91  return -1;
92  }
93 }