httpdate: minor size reduction in DSO
[unicorn.git] / ext / unicorn_http / httpdate.c
blobbf54fdd08054a5f2df1f58bf89ff3911179ecc1c
1 #include <ruby.h>
2 #include <time.h>
3 #include <stdio.h>
5 static const size_t buf_capa = sizeof("Thu, 01 Jan 1970 00:00:00 GMT");
6 static VALUE buf;
7 static char *buf_ptr;
8 static const char week[] = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
9 static const char months[] = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
10 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
12 /* for people on wonky systems only */
13 #ifndef HAVE_GMTIME_R
14 static struct tm * my_gmtime_r(time_t *now, struct tm *tm)
16 struct tm *global = gmtime(now);
17 if (global)
18 *tm = *global;
19 return tm;
21 # define gmtime_r my_gmtime_r
22 #endif
26 * Returns a string which represents the time as rfc1123-date of HTTP-date
27 * defined by RFC 2616:
29 * day-of-week, DD month-name CCYY hh:mm:ss GMT
31 * Note that the result is always GMT.
33 * This method is identical to Time#httpdate in the Ruby standard library,
34 * except it is implemented in C for performance. We always saw
35 * Time#httpdate at or near the top of the profiler output so we
36 * decided to rewrite this in C.
38 * Caveats: it relies on a Ruby implementation with the global VM lock,
39 * a thread-safe version will be provided when a Unix-only, GVL-free Ruby
40 * implementation becomes viable.
42 static VALUE httpdate(VALUE self)
44 static time_t last;
45 time_t now = time(NULL); /* not a syscall on modern 64-bit systems */
46 struct tm tm;
48 if (last == now)
49 return buf;
50 last = now;
51 gmtime_r(&now, &tm);
53 /* we can make this thread-safe later if our Ruby loses the GVL */
54 snprintf(buf_ptr, buf_capa,
55 "%s, %02d %s %4d %02d:%02d:%02d GMT",
56 week + (tm.tm_wday * 4),
57 tm.tm_mday,
58 months + (tm.tm_mon * 4),
59 tm.tm_year + 1900,
60 tm.tm_hour,
61 tm.tm_min,
62 tm.tm_sec);
64 return buf;
67 void init_unicorn_httpdate(void)
69 VALUE mod = rb_const_get(rb_cObject, rb_intern("Unicorn"));
70 mod = rb_define_module_under(mod, "HttpResponse");
72 buf = rb_str_new(0, buf_capa - 1);
73 rb_global_variable(&buf);
74 buf_ptr = RSTRING_PTR(buf);
75 httpdate(Qnil);
77 rb_define_method(mod, "httpdate", httpdate, 0);