From 175561f8dd142d6db89bc6eb8054834da26ee0d9 Mon Sep 17 00:00:00 2001 From: akr Date: Thu, 1 Jan 2009 10:37:41 +0000 Subject: * ext/socket/mkconstants.rb: generate family_to_str. * ext/socket/socket.c (ipaddr): use family_to_str. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@21244 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ext/socket/mkconstants.rb | 43 +++++++++++++++++++++++++++++++++++++++++++ ext/socket/socket.c | 30 +++++++----------------------- 2 files changed, 50 insertions(+), 23 deletions(-) (limited to 'ext/socket') diff --git a/ext/socket/mkconstants.rb b/ext/socket/mkconstants.rb index 6c6be0f6e2..09f0f030c7 100644 --- a/ext/socket/mkconstants.rb +++ b/ext/socket/mkconstants.rb @@ -93,6 +93,43 @@ ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_name_to_int(str_var, len_var, } EOS +MAYBE_ALIAS = [ + ["AF_UNIX", "AF_LOCAL"] +] + +def each_alias(pat) + h = {} + each_name(pat) {|name| + h[name] = [name] + } + MAYBE_ALIAS.each {|names| + a = [] + names.each {|n| + a << n if h.delete n + } + h[a.first] = a + } + h.each_value {|names| + yield names + } +end + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_int_to_name(int_var, pat)") + switch (<%=int_var%>) { +% each_alias(pat) {|names| +% names.each_with_index {|n, i| +% cond = ["defined(#{n})"] +% (0...i).each {|j| cond << "(!defined(#{names[j]}) || #{n} != #{names[j]})" } +#if <%=cond.join(" && ")%> + case <%=n%>: return <%=c_str n%>; +#endif +% } +% } + default: + return NULL; + } +EOS + result << ERB.new(<<'EOS', nil, '%').result(binding) static void init_constants(VALUE mConst) @@ -127,6 +164,12 @@ socktype_to_int(char *str, int len) <%= gen_name_to_int("str", "len", /\ASOCK_/) %> } +static char * +family_to_str(int val) +{ +<%= gen_int_to_name("val", /\AAF_/) %> +} + EOS if opt_o diff --git a/ext/socket/socket.c b/ext/socket/socket.c index 61f72e7ea6..f6fe3955fb 100644 --- a/ext/socket/socket.c +++ b/ext/socket/socket.c @@ -981,6 +981,8 @@ sock_addrinfo(VALUE host, VALUE port, int socktype, int flags) return sock_getaddrinfo(host, port, &hints); } +static char *family_to_str(int val); + static VALUE ipaddr(struct sockaddr *sockaddr, int norevlookup) { @@ -988,32 +990,14 @@ ipaddr(struct sockaddr *sockaddr, int norevlookup) VALUE ary; int error; char hbuf[1024], pbuf[1024]; + char *name; - switch (sockaddr->sa_family) { - case AF_UNSPEC: - family = rb_str_new2("AF_UNSPEC"); - break; - case AF_INET: - family = rb_str_new2("AF_INET"); - break; -#ifdef INET6 - case AF_INET6: - family = rb_str_new2("AF_INET6"); - break; -#endif -#ifdef AF_LOCAL - case AF_LOCAL: - family = rb_str_new2("AF_LOCAL"); - break; -#elif AF_UNIX - case AF_UNIX: - family = rb_str_new2("AF_UNIX"); - break; -#endif - default: + name = family_to_str(sockaddr->sa_family); + if (name) + family = rb_str_new2(name); + else { sprintf(pbuf, "unknown:%d", sockaddr->sa_family); family = rb_str_new2(pbuf); - break; } addr1 = Qnil; -- cgit v1.2.3