00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include <iostream>
00023 #include <fstream>
00024 #include <stdexcept>
00025 #include <cassert>
00026 #include <stdio.h>
00027 #include <stdlib.h>
00028 #include <cstring>
00029 #include <string.h>
00030 #include "math.h"
00031 #include "mempool.h"
00032 #include "htable.h"
00033
00034 #include "ngramcache.h"
00035
00036 using namespace std;
00037
00038 ngramcache::ngramcache(int n,int size,int maxentries){
00039 ngsize=n;
00040 infosize=size;
00041 maxn=maxentries;
00042 entries=0;
00043 ht=new htable(maxn * 2, ngsize * sizeof(int),INT,NULL);
00044 mp=new mempool(ngsize * sizeof(int)+infosize,1000000);
00045 accesses=0;
00046 hits=0;
00047 };
00048
00049 ngramcache::~ngramcache(){
00050
00051
00052 delete ht;delete mp;
00053 };
00054
00055
00056
00057 void ngramcache::reset(int n){
00058
00059 delete ht;delete mp;
00060 if (n>0) maxn=n;
00061 ht=new htable(maxn * 2, ngsize * sizeof(int),INT,NULL);
00062 mp=new mempool(ngsize * sizeof(int)+infosize,1000000);
00063 entries=0;
00064 };
00065
00066
00067
00068
00069 char* ngramcache::get(const int* ngp,char* info){
00070 char *found;
00071
00072 accesses++;
00073 if ((found=ht->search((char *)ngp,HT_FIND))){
00074 if (info) memcpy(info,found+ngsize*sizeof(int),infosize);
00075 hits++;
00076 };
00077 return found;
00078 };
00079
00080
00081 int ngramcache::add(const int* ngp,const char* info){
00082
00083 char* entry=mp->allocate();
00084 memcpy(entry,(char*) ngp,sizeof(int) * ngsize);
00085 memcpy(entry + ngsize * sizeof(int),(char *)info,infosize);
00086 char *found=ht->search((char *)entry,HT_ENTER);
00087 assert(found == entry);
00088 entries++;
00089 return 1;
00090 }
00091
00092 void ngramcache::stat(){
00093 cerr << "ngramcache stats: entries=" << entries << " acc=" << accesses << " hits=" << hits << "\n";
00094 };