- 论坛徽章:
- 6
|
出于可读性和性能的原因,
一般高手都是这样做的,
程序很简洁,维护也很简单
GET action = 0
SET action = -1
HEAD action = 0
POST action = 2
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef enum {
- M_NOACTION = -1,
- M_GET,
- M_PATCH,
- M_POST,
- M_PROPFIND,
- M_PROPPATCH,
- M_PUT
- } Method;
- typedef struct {
- char *key;
- Method action;
- } Table;
- Method foo(char *);
- int COMPARE(const void *, const void *);
- int main() {
- char *test[] = {"GET", "SET", "HEAD", "POST"};
- for (int i = 0; i < 4; i++) {
- Method m = foo(test[i]);
- printf("%s action = %d\n", test[i], m);
- }
- }
- int COMPARE(const void *x, const void *y) {
- Table *a = (Table *)x;
- Table *b = (Table *)y;
- return strcmp(a->key, b->key);
- }
- Method foo(char *act) {
- static Table action[] = {
- {"GET", M_GET},
- {"HEAD", M_GET},
- {"PATCH", M_PATCH},
- {"POST", M_POST},
- {"PROPFIND", M_PROPFIND},
- {"PROPPATCH", M_PROPPATCH},
- {"PUT", M_PUT},
- };
- int size = sizeof(action) / sizeof(Table);
- Table key = {.key = act};
- Table *r = (Table *)bsearch(&key, action, size, sizeof(Table), COMPARE);
- return r ? r->action : M_NOACTION;
- }
复制代码 |
|