Grafalgo
Library of useful data structures and algorithms
/Users/jst/src/grafalgo/cpp/dataStructures/misc/Lpm.cpp
00001 #include "stdinc.h"
00002 #include "lmp.h"
00003 
00004 lmp::lmp(int N1) : N(N1) {
00005         vec = new nodeItem[N];  
00006         n = 0;
00007 }
00008 
00009 lmp::~lmp() { delete [] vec; }
00010 
00011 int lmp::lookup(ipa_t adr) {
00012 // Lookup adr in vec and return nexthop for longest match.
00013 // Return Null if no match.
00014         int best = -1;
00015         for (int i = 0; i < n; i++) {
00016                 int s = 32 - vec[i].len;
00017                 if (adr >> s != vec[i].pref >> s) continue;
00018                 if (best < 0 || vec[i].len > vec[best].len)
00019                         best = i;
00020         }
00021         if (best < 0) return Null;
00022         return vec[best].nexthop;
00023 }
00024 
00025 bool lmp::insert(ipa_t prefix, int len, int next) {
00026 // Add (prefix, next hop) pair to list of prefixes.
00027 // If prefix already present, replaces the nexthop value.
00028         for (int i = 0; i < n; i++) {
00029                 if (vec[i].len != len) continue;
00030                 int s = 32 - len;
00031                 if (prefix >> s != vec[i].pref >> s) continue;
00032                 vec[i].nexthop = next;
00033                 return true;
00034         }
00035         if (n == N) return false;
00036         vec[n].pref = prefix; vec[n].len = len; vec[n].nexthop = next;
00037         n++;
00038         return true;
00039 }
00040 
00041 void lmp::remove(ipa_t prefix, int len) {
00042 // Remove the specified prefix.
00043         for (int i = 0; i < n; i++) {
00044                 if (vec[i].len != len) continue;
00045                 int s = 32 - len;
00046                 if (prefix >> s != vec[i].pref >> s) continue;
00047                 vec[i] = vec[--n];
00048                 return;
00049         }
00050 }
00051 
00052 // Print all prefixes in the list.
00053 void lmp::print() {
00054         for (int i = 0; i < n; i++) {
00055                 printf("%d.%d.%d.%d/%d => %d\n",
00056                         (vec[i].pref >> 24) & 0xff,
00057                         (vec[i].pref >> 16) & 0xff,
00058                         (vec[i].pref >> 8) & 0xff,
00059                          vec[i].pref & 0xff, vec[i].len, vec[i].nexthop);
00060         }
00061 }
 All Classes Files Functions Variables Typedefs Friends