Portability patches from Kevin Dalley for Freebsd 4.0.
[m6w6/libmemcached] / lib / memcached_hosts.c
index fac037070c8a6e2b7da59a3efe74a8668eb93d02..5661e541180fdcb64a0e1b0d8cd433f59b322bfc 100644 (file)
@@ -6,11 +6,39 @@ static memcached_return server_add(memcached_st *ptr, char *hostname,
                                    unsigned int port,
                                    memcached_connection type);
 
+#define MEMCACHED_WHEEL_SIZE 1024
+#define MEMCACHED_STRIDE 4
+static void rebalance_wheel(memcached_st *ptr)
+{
+  unsigned int x;
+  unsigned int y;
+  unsigned int latch;
+  unsigned int range;
+
+  range= (MEMCACHED_WHEEL_SIZE / ptr->number_of_hosts);
+
+  /* Seed the Wheel */
+  memset(ptr->wheel, 0, sizeof(unsigned int) * MEMCACHED_WHEEL_SIZE);
+
+  for (latch= y= x= 0; x < MEMCACHED_WHEEL_SIZE; x++, latch++)
+  {
+    if (latch == MEMCACHED_STRIDE)
+    {
+      y++;
+      if (y == ptr->number_of_hosts)
+        y= 0;
+      latch= 0;
+    }
+
+    ptr->wheel[x]= y;
+  }
+}
+
 static void host_reset(memcached_server_st *host, char *hostname, unsigned int port,
                        memcached_connection type)
 {
   memset(host,  0, sizeof(memcached_server_st));
-  host->hostname= strdup(hostname);
+  strncpy(host->hostname, hostname, MEMCACHED_MAX_HOST_LENGTH - 1);
   host->port= port;
   host->fd= -1;
   host->type= type;
@@ -41,13 +69,15 @@ memcached_return memcached_server_push(memcached_st *ptr, memcached_server_st *l
                                    
   for (x= 0; x < count; x++)
   {
-    WATCHPOINT_ASSERT(list[x].hostname);
+    WATCHPOINT_ASSERT(list[x].hostname[0] != 0);
     host_reset(&ptr->hosts[ptr->number_of_hosts], list[x].hostname, 
                list[x].port, list[x].type);
     ptr->number_of_hosts++;
   }
   ptr->hosts[0].count= ptr->number_of_hosts;
 
+  rebalance_wheel(ptr);
+
   return MEMCACHED_SUCCESS;
 }
 
@@ -104,6 +134,8 @@ static memcached_return server_add(memcached_st *ptr, char *hostname,
   ptr->number_of_hosts++;
   ptr->hosts[0].count++;
 
+  rebalance_wheel(ptr);
+
   LIBMEMCACHED_MEMCACHED_SERVER_ADD_END();
 
   return MEMCACHED_SUCCESS;
@@ -146,7 +178,6 @@ memcached_server_st *memcached_server_list_append(memcached_server_st *ptr,
 
 unsigned int memcached_server_list_count(memcached_server_st *ptr)
 {
-
   if (ptr == NULL)
     return 0;
 
@@ -160,8 +191,9 @@ void memcached_server_list_free(memcached_server_st *ptr)
   if (ptr == NULL)
     return;
 
-  for (x= 0; x < ptr[0].count; x++)
-    free(ptr[x].hostname);
+  for (x= 0; x < ptr->count; x++)
+    if (ptr[x].address_info)
+      freeaddrinfo(ptr[x].address_info);
 
   free(ptr);
 }