• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * lws-api-test-lwsac
3  *
4  * Written in 2010-2019 by Andy Green <andy@warmcat.com>
5  *
6  * This file is made available under the Creative Commons CC0 1.0
7  * Universal Public Domain Dedication.
8  */
9 
10 #include <libwebsockets.h>
11 
12 struct mytest {
13 	int payload;
14 	/* notice doesn't have to be at start of struct */
15 	lws_list_ptr list_next;
16 	/* a struct can appear on multiple lists too... */
17 };
18 
19 /* converts a ptr to struct mytest .list_next to a ptr to struct mytest */
20 #define list_to_mytest(p) lws_list_ptr_container(p, struct mytest, list_next)
21 
main(int argc,const char ** argv)22 int main(int argc, const char **argv)
23 {
24 	int n, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE, acc;
25 	lws_list_ptr list_head = NULL, iter;
26 	struct lwsac *lwsac = NULL;
27 	struct mytest *m;
28 	const char *p;
29 
30 	if ((p = lws_cmdline_option(argc, argv, "-d")))
31 		logs = atoi(p);
32 
33 	lws_set_log_level(logs, NULL);
34 	lwsl_user("LWS API selftest: lwsac\n");
35 
36 	/*
37 	 * 1) allocate and create 1000 struct mytest in a linked-list
38 	 */
39 
40 	for (n = 0; n < 1000; n++) {
41 		m = lwsac_use(&lwsac, sizeof(*m), 0);
42 		if (!m)
43 			return -1;
44 		m->payload = n;
45 
46 		lws_list_ptr_insert(&list_head, &m->list_next, NULL);
47 	}
48 
49 	/*
50 	 * 2) report some debug info about the lwsac state... those 1000
51 	 * allocations actually only required 4 mallocs
52 	 */
53 
54 	lwsac_info(lwsac);
55 
56 	/* 3) iterate the list, accumulating the payloads */
57 
58 	acc = 0;
59 	iter = list_head;
60 	while (iter) {
61 		m = list_to_mytest(iter);
62 		acc += m->payload;
63 
64 		lws_list_ptr_advance(iter);
65 	}
66 
67 	if (acc != 499500) {
68 		lwsl_err("%s: FAIL acc %d\n", __func__, acc);
69 
70 		return 1;
71 	}
72 
73 	/*
74 	 * 4) deallocate everything (lwsac is also set to NULL).  It just
75 	 *    deallocates the 4 mallocs, everything in there is gone accordingly
76 	 */
77 
78 	lwsac_free(&lwsac);
79 
80 	lwsl_user("Completed: PASS\n");
81 
82 	return 0;
83 }
84