comparison nnchat.c @ 129:4235ff4ced04

"Optimize" protocol handling.
author Matti Hamalainen <ccr@tnsp.org>
date Sat, 30 Oct 2010 15:07:03 +0300
parents 713879a7ca10
children 352ec3c300e4
comparison
equal deleted inserted replaced
128:713879a7ca10 129:4235ff4ced04
513 } 513 }
514 514
515 515
516 typedef struct { 516 typedef struct {
517 char *cmd; 517 char *cmd;
518 ssize_t len;
518 int (*handler)(int, const char *); 519 int (*handler)(int, const char *);
519 } protocmd_t; 520 } protocmd_t;
520 521
521 522
522 static const protocmd_t protoCmds[] = { 523 static protocmd_t protoCmds[] = {
523 { "<USER>", handleUser }, 524 { "<USER>", -1, handleUser },
524 { "<LOGIN_", handleLogin }, 525 { "<LOGIN_", -1, handleLogin },
525 { "<DELETE_USER>", handleDeleteUser }, 526 { "<DELETE_USER>", -1, handleDeleteUser },
526 { "<ADD_USER>", handleAddUser }, 527 { "<ADD_USER>", -1, handleAddUser },
527 { "<NUMCLIENTS>", handleFoo }, 528 { "<NUMCLIENTS>", -1, handleFoo },
528 { "<BOOT />", handleBoot }, 529 { "<BOOT />", -1, handleBoot },
529 }; 530 };
530 531
531 static const int nprotoCmds = sizeof(protoCmds) / sizeof(protoCmds[0]); 532 static const int nprotoCmds = sizeof(protoCmds) / sizeof(protoCmds[0]);
532 533
533 534
534 int handleProtocol(const int sock, const char *buf, const size_t bufLen) 535 int handleProtocol(const int sock, const char *buf, const ssize_t bufLen)
535 { 536 {
536 int i; 537 int i;
537 538
538 for (i = 0; i < nprotoCmds; i++) { 539 for (i = 0; i < nprotoCmds; i++) {
539 size_t cmdLen = strlen(protoCmds[i].cmd); 540 ssize_t cmdLen = protoCmds[i].len;
540 if (cmdLen < bufLen && !strncmp(buf, protoCmds[i].cmd, cmdLen)) { 541 if (cmdLen < 0)
542 cmdLen = protoCmds[i].len = strlen(protoCmds[i].cmd);
543
544 if (cmdLen < bufLen && !strncmp(buf, protoCmds[i].cmd, cmdLen))
541 return protoCmds[i].handler(sock, buf + cmdLen); 545 return protoCmds[i].handler(sock, buf + cmdLen);
542 }
543 } 546 }
544 547
545 return 1; 548 return 1;
546 } 549 }
547 550