1/* $NetBSD: name_code.c,v 1.2 2017/02/14 01:16:49 christos Exp $ */ 2 3/*++ 4/* NAME 5/* name_code 3 6/* SUMMARY 7/* name to number table mapping 8/* SYNOPSIS 9/* #include <name_code.h> 10/* 11/* typedef struct { 12/* .in +4 13/* const char *name; 14/* int code; 15/* .in -4 16/* } NAME_CODE; 17/* 18/* int name_code(table, flags, name) 19/* const NAME_CODE *table; 20/* int flags; 21/* const char *name; 22/* 23/* const char *str_name_code(table, code) 24/* const NAME_CODE *table; 25/* int code; 26/* DESCRIPTION 27/* This module does simple name<->number mapping. The process 28/* is controlled by a table of (name, code) values. 29/* The table is terminated with a null pointer and a code that 30/* corresponds to "name not found". 31/* 32/* name_code() looks up the code that corresponds with the name. 33/* The lookup is case insensitive. The flags argument specifies 34/* zero or more of the following: 35/* .IP NAME_CODE_FLAG_STRICT_CASE 36/* String lookups are case sensitive. 37/* .PP 38/* For convenience the constant NAME_CODE_FLAG_NONE requests 39/* no special processing. 40/* 41/* str_name_code() translates a number to its equivalent string. 42/* DIAGNOSTICS 43/* When the search fails, the result is the "name not found" code 44/* or the null pointer, respectively. 45/* LICENSE 46/* .ad 47/* .fi 48/* The Secure Mailer license must be distributed with this software. 49/* AUTHOR(S) 50/* Wietse Venema 51/* IBM T.J. Watson Research 52/* P.O. Box 704 53/* Yorktown Heights, NY 10598, USA 54/*--*/ 55 56/* System library. */ 57 58#include <sys_defs.h> 59#include <string.h> 60 61/* Utility library. */ 62 63#include <name_code.h> 64 65/* name_code - look up code by name */ 66 67int name_code(const NAME_CODE *table, int flags, const char *name) 68{ 69 const NAME_CODE *np; 70 int (*lookup) (const char *, const char *); 71 72 if (flags & NAME_CODE_FLAG_STRICT_CASE) 73 lookup = strcmp; 74 else 75 lookup = strcasecmp; 76 77 for (np = table; np->name; np++) 78 if (lookup(name, np->name) == 0) 79 break; 80 return (np->code); 81} 82 83/* str_name_code - look up name by code */ 84 85const char *str_name_code(const NAME_CODE *table, int code) 86{ 87 const NAME_CODE *np; 88 89 for (np = table; np->name; np++) 90 if (code == np->code) 91 break; 92 return (np->name); 93} 94