wangzhengquan
2020-09-25 00dba6082e245d917cb7d6eed3c627211ff41cd7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "usg_common.h"
#include "usg_typedef.h"
 
#define ACTION_LIDENTIFIER "<**"
#define ACTION_RIDENTIFIER "**>"
#define TOPIC_LIDENTIFIER "{"
#define TOPIC_RIDENTIFIER "}"
 
int parse_pubsub_topic(char *str, char **_action, char **_topic, size_t *head_len ) {
 char *ptr = str;
 char *str_end_ptr = str + strlen(str);
 char *action_start_ptr;
 char *action_end_ptr;
 size_t action_len = 0;
 
 char *topic_start_ptr;
 char *topic_end_ptr;
 size_t topic_len = 0;
 
 // if (strlen(identifier) > strlen(str)) {
 //  return 0;
 // }
 
 if (strncmp(ptr, ACTION_LIDENTIFIER, strlen(ACTION_LIDENTIFIER)) == 0) {
  ptr += strlen(ACTION_LIDENTIFIER);
  action_start_ptr = ptr;
  while(strncmp(++ptr, ACTION_RIDENTIFIER, strlen(ACTION_RIDENTIFIER)) != 0) {
    if(ptr >= str_end_ptr) {
      return 0;
    }
  }
// printf("%s\n", ptr);
  action_end_ptr = ptr;
  action_len = action_end_ptr - action_start_ptr;
  ptr += strlen(ACTION_RIDENTIFIER);
// printf("%s\n", ptr);
// printf("%s\n", str_end_ptr-1);
  if(strncmp(ptr, TOPIC_LIDENTIFIER, strlen(TOPIC_LIDENTIFIER)) == 0 ) {
    topic_start_ptr = ptr+strlen(TOPIC_LIDENTIFIER);
   
 
    while(strncmp(++ptr, TOPIC_RIDENTIFIER, strlen(TOPIC_RIDENTIFIER)) != 0) {
      if(ptr >= str_end_ptr) {
        return 0;
      }
    }
    topic_end_ptr = ptr;
    topic_len = topic_end_ptr - topic_start_ptr;
    
    ptr += strlen(TOPIC_RIDENTIFIER);
   
  } else {
    return 0;
  }
 } else {
  return 0;
 }
 
 char *topic = (char *)calloc(1, topic_len+1);
 strncpy(topic, topic_start_ptr, topic_len);
 *_topic = topic;
 
 char *action = (char *)calloc(1, action_len+1);
 strncpy(action, action_start_ptr, action_len);
 *_action = action;
 *head_len = ptr-str;
 
 return 1;
}
 
int main() {
 char *action;
 size_t action_len;
 char *topic;
 size_t head_len;
  
 char *str = "<**pub**>{经济}abcdef";
 if(parse_pubsub_topic(str, &action, &topic, &head_len)) {
  printf("action:%s\n", action);
  printf("topic:%s\n", topic);
  printf("content:%s\n", str+head_len);
  free(action);
  free(topic);
 } else {
  printf("===========error==============\n");
 }
 
 
 
}