trema/trema — pull request #198 by userlocalhost2000 (2012-08-13 14:15:44+00:00)
Title: add iterate_list() function

Dear All

I always use library functions that trema has prepared. One of them is the linked-list.

I feel it is useful. But I want to use this transparently, without awareness of linked-list construction.

Concretely, I hate to write linked-list loop and conditional statements at any place.
When the program is longer, the similar statements like following more appear.

for ( element = *switches; element != NULL; element = element->next ) {
if ( *( ( uint64_t * ) element->data ) == datapath_id ) {
... something ...
}
}

To deal in list_element transparently, I added a function in [ lib/linked_list.c ].
This function abstract iterate processing and extraction of data that linked-list has.

e.g.
With this change, linked-list loop statement can be eliminated from switch_info of Trema example.

Thank you.

De: Hiroyasu OHYAMA

===

diff --git a/src/examples/switch_monitor/switch_monitor.c b/src/examples/switch_monitor/switch_monitor.c
index 99c319e..b22cf7b 100644
--- a/src/examples/switch_monitor/switch_monitor.c
+++ b/src/examples/switch_monitor/switch_monitor.c
@@ -43,19 +51,23 @@ create_switches( list_element **switches ) {
create_list( switches );
}

+static bool
+release_switch_info( void *data, void *user_data ) {
+ UNUSED( user_data );
+
+ if( data != NULL ) {
+ xfree( data );
+ }
+
+ return false;
+}

static void
delete_switches( list_element *switches ) {
- list_element *element;
- for ( element = switches; element != NULL; element = element->next ) {
- if ( element->data != NULL ) {
- xfree( element->data );
- }
- }
+ iterate_list( switches, release_switch_info, NULL );
delete_list( switches );
}

-
static void
insert_datapath_id( list_element **switches, uint64_t datapath_id ) {
list_element *element = NULL;
@@ -81,17 +93,24 @@ insert_datapath_id( list_element **switches, uint64_t datapath_id ) {
}
}

+static bool
+get_switch_info( void *data, void *user_data ) {
+ uint64_t *datapath_id = (uint64_t *)user_data;
+ bool ret = false;
+
+ if ( *( ( uint64_t * ) data ) == *datapath_id ) {
+ ret = true;
+ }
+
+ return ret;
+}

static void
delete_datapath_id( list_element **switches, uint64_t datapath_id ) {
- list_element *element = NULL;
- for ( element = *switches; element != NULL; element = element->next ) {
- if ( *( ( uint64_t * ) element->data ) == datapath_id ) {
- void *data = element->data;
- delete_element( switches, data );
- xfree( data );
- return;
- }
+ void *data = iterate_list( *switches, get_switch_info, ( void * )&datapath_id );
+ if( data != NULL ) {
+ delete_element( switches, data );
+ xfree( data );
}
// not found
}