mem.cpp

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) Sergey P. Derevyago, 2008.
00003  *
00004  * Permission to copy, use, modify, sell and distribute this software is granted
00005  * provided this copyright notice appears in all copies.
00006  * This software is provided "as is" without express or implied warranty, and
00007  * with no claim as to its suitability for any purpose.
00008  *
00009  */
00010 
00015 #include <ders/mem.hpp>
00016 #include <string.h>
00017 
00018 namespace ders {  // ::ders
00019 
00020 void* mem_find(void* p1, int sz1, char ch)
00021 {
00022  return (sz1>0) ? memchr(p1, ch, sz1) : 0;
00023 }
00024 
00025 void* mem_rev_find(void* p1, int sz1, char ch)
00026 {
00027  char *e=(char*)p1+sz1-1, *b=e-sz1;
00028 
00029  for ( ; e>=b+4; e-=4) {
00030      if (*(e-0)==ch) return e-0;
00031      if (*(e-1)==ch) return e-1;
00032      if (*(e-2)==ch) return e-2;
00033      if (*(e-3)==ch) return e-3;
00034  }
00035 
00036  switch (e-b) {
00037         case 3:
00038              if (*(e-0)==ch) return e-0;
00039              if (*(e-1)==ch) return e-1;
00040              if (*(e-2)==ch) return e-2;
00041              break;
00042         case 2:
00043              if (*(e-0)==ch) return e-0;
00044              if (*(e-1)==ch) return e-1;
00045              break;
00046         case 1:
00047              if (*(e-0)==ch) return e-0;
00048              break;
00049  }
00050 
00051  return 0;
00052 }
00053 
00054 void* mem_find(void* p1, int sz1, const void* p2, int sz2)
00055 {
00056  if (sz1<=0 || sz2<=0) return 0;
00057 
00058  for (char *b=(char*)p1, *e=b+sz1-sz2+1; b<e; ) {
00059      char* ptr=(char*)mem_find(b, e-b, *(char*)p2);
00060      if (!ptr) return 0;
00061 
00062      if (memcmp(ptr+1, (char*)p2+1, sz2-1)==0) return ptr;
00063      b=ptr+1;
00064  }
00065 
00066  return 0;
00067 }
00068 
00069 void* mem_rev_find(void* p1, int sz1, const void* p2, int sz2)
00070 {
00071  if (sz1<=0 || sz2<=0) return 0;
00072 
00073  for (char *b=(char*)p1, *e=b+sz1-sz2+1; b<e; ) {
00074      char* ptr=(char*)mem_rev_find(b, e-b, *(char*)p2);
00075      if (!ptr) return 0;
00076 
00077      if (memcmp(ptr+1, (char*)p2+1, sz2-1)==0) return ptr;
00078      e=ptr;
00079  }
00080 
00081  return 0;
00082 }
00083 
00084 }  // namespace ::ders
00085 

Generated on Tue Dec 8 11:35:32 2009 for derslib by  doxygen 1.5.5