commit d31aa6abec461422e8629aeac278f96e163e5b88 Author: Gerardo Date: Mon Apr 6 13:07:26 2020 +0200 Version inicial en v2017 partiendo de la v2008 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..05518dc --- /dev/null +++ b/.gitignore @@ -0,0 +1,64 @@ +/lib +/bin +/includes +/utiles.suo +/utiles.ncb +/utiles.aps +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates +*.Cache +*.bak +*.ncb +/Debug/vc90.pdb +/Debug/_app.obj +/Debug/_error.obj +/Debug/_log.obj +/Debug/_proceso.obj +/Debug/ascii_file.obj +/Debug/b_file.obj +/Debug/bmp_control.obj +/Debug/BuildLog.htm +/Debug/cola_asincrona.obj +/Debug/control_usu_con.obj +/Debug/Csock_cl.obj +/Debug/csv_file.obj +/Debug/DijkstraUtiles.obj +/Debug/dir_manager.obj +/Debug/gconect_srv.obj +/Debug/ini_file.obj +/Debug/lock.obj +/Debug/mapmatrix.obj +/Debug/mt.dep +/Debug/proceso_cliente.obj +/Debug/puerto_com.obj +/Debug/sock_http.obj +/Debug/sock_sv.obj +/Debug/static_array.obj +/Debug/static_array_ord.obj +/Debug/static_cola.obj +/Debug/stdafx.obj +/Debug/str_array.obj +/Debug/TaskProcess.obj +/Debug/th.obj +/Debug/utiles.dll +/Debug/utiles.dll.embed.manifest +/Debug/utiles.dll.embed.manifest.res +/Debug/utiles.dll.intermediate.manifest +/Debug/utiles.exp +/Debug/utiles.ilk +/Debug/utiles.lib +/Debug/utiles.obj +/Debug/utiles.pch +/Debug/utiles.pdb +/Debug/utiles.res +/Debug/utiles_dll.obj +/Debug/utl.obj +/Debug/vc90.idb diff --git a/Backup/utiles.sln b/Backup/utiles.sln new file mode 100644 index 0000000..82cc536 --- /dev/null +++ b/Backup/utiles.sln @@ -0,0 +1,26 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "utiles", "utiles.vcproj", "{AA58C828-7025-4A4C-868E-76B8902AF6BB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Debug|Win32.ActiveCfg = Debug|Win32 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Debug|Win32.Build.0 = Debug|Win32 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Debug|x64.ActiveCfg = Debug|x64 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Debug|x64.Build.0 = Debug|x64 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Release|Win32.ActiveCfg = Release|Win32 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Release|Win32.Build.0 = Release|Win32 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Release|x64.ActiveCfg = Release|x64 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/CartoBase.cpp b/CartoBase.cpp new file mode 100644 index 0000000..7039531 --- /dev/null +++ b/CartoBase.cpp @@ -0,0 +1,695 @@ +#include "StdAfx.h" +#include "CartoBase.h" +#include "CartoBaseShpManager.h" +#include "CartoBaseDBFManager.h" +#include "dir_manager.h" +#include "Fdbf.h" +//***************************************************************************************** +CartoBase::CartoBase(void) +{ + ref = 0; + typeIA = IntIa; + strcpy(iaName, "Ia"); + iaEx =this; +} +//***************************************************************************************** + +CartoBase::~CartoBase(void) +{ +} +//***************************************************************************************** +int CartoBase::getNumberEntities() +{ + return _entities.n; +} +//***************************************************************************************** +double* CartoBase::getPto(int i) +{ + return _points[i].pts; +} +//***************************************************************************************** +int CartoBase::getNumberPtos() +{ + return _points.n; +} +//***************************************************************************************** +CartoBaseInfoEntity CartoBase::getEntity(int i) +{ + return get(i); +} +//***************************************************************************************** +CartoBaseInfoEntity CartoBase::get(int i) +{ + return CartoBaseInfoBuilder::get(i, this); +} +//***************************************************************************************** +CartoBaseInfoEntity CartoBase::getRef(int r) +{ + return CartoBaseInfoBuilder::get(refIndex[r], this); +} +//***************************************************************************************** +int CartoBase::getEntityRef( int ientity ) +{ + return _entities[ientity].ref; +} +//***************************************************************************************** +bool CartoBase::add(CartoEntity& element) +{ + bool res = 0<=element.CopyInTo(this); + if(res && iaEx && typeIA != NIa) + iaEx->IaAdd(_entities[_entities.n-1].ref); + return res; +} +//***************************************************************************************** +bool CartoBase::add(CartoBase& cad) +{ + return false; +} +//***************************************************************************************** +bool CartoBase::grabar(char *path) +{ + Cb_file f; + if(!f.abre(path,2,1)) + return false; + return grabar(&f); +} +//***************************************************************************************** +bool CartoBase::leer(char *path) +{ + Cb_file f; + if(!f.abre(path,1,0,true)) + return false; + return leer(&f); +} +//***************************************************************************************** +bool CartoBase::grabar(Cb_file *f) +{ + char st[16]; + int version; + memset(st,0,16); + strcpy(st,TYPE_FILE); + if(!f->escribe(st, 16)) + return false; + version = VERSION_CART_BASE; + if(!f->escribe(&version, sizeof(version))) + return false; + + if(!f->escribe(&_defaultColor, sizeof(_defaultColor))) + return false; + if(!f->escribe(&_defaultpaintedProps, sizeof(_defaultpaintedProps))) + return false; + if(!_entities.graba(f)) + return false; + if(!_points.graba(f)) + return false; + if(!_lines.graba(f)) + return false; + if(!_paintedProps.graba(f)) + return false; + if(!_colors.graba(f)) + return false; + return true; +} +//***************************************************************************************** +bool CartoBase::leer (Cb_file* f) +{ + char st[16]; + int version; + memset(st,0,16); + if(!f->lee(st, 16) || strcmp(st, TYPE_FILE)) + return false; + if(!f->lee(&version, sizeof(version)) || version!= VERSION_CART_BASE) + return false; + if(!f->lee(&_defaultColor, sizeof(_defaultColor))) + return false; + + if(!f->lee(&_defaultpaintedProps, sizeof(_defaultpaintedProps))) + return false; + _entities.n = 0; + if(!_entities.leer(f)) + return false; + _points.n = 0; + if(!_points.leer(f)) + return false; + _lines.n = 0; + if(!_lines.leer(f)) + return false; + _paintedProps.n = 0; + if(!_paintedProps.leer(f)) + return false; + _colors.n = 0; + if(!_colors.leer(f)) + return false; + iniIndexRef(); + return true; +} +//***************************************************************************************** +int CartoBase::add(CartoBaseEntity* src) +{ + if(_entities+(*src)) + { + _entities[_entities.n-1].ref = ref; + refIndex[ref++] = _entities.n-1; + return _entities.n-1; + } + return -1; +} +//***************************************************************************************** +int CartoBase::add(CartoBasePoint* src) +{ + if(_points+(*src)) + return _points.n-1; + return -1; +} +//***************************************************************************************** +int CartoBase::add(CartoBaseLine* src) +{ + if(_lines+(*src)) + return _lines.n-1; + return -1; +} +//***************************************************************************************** +int CartoBase::add(CartoBasePaintedProps* src) +{ + if(_paintedProps+(*src)) + return _paintedProps.n-1; + return -1; +} +//***************************************************************************************** +int CartoBase::add(CartoBaseColor* src) +{ + if(_colors+(*src)) + return _colors.n-1; + return -1; +} +//***************************************************************************************** +int CartoBase::addDefaultPaintedProps() +{ + _defaultpaintedProps.color = _colors.n; + _colors+_defaultColor; + _paintedProps+_defaultpaintedProps; + _defaultpaintedProps.color = -1; + return _paintedProps.n-1; +} +//***************************************************************************************** +void CartoBase::del() +{ + _entities.n=0; + _points.n=0; + _lines.n=0; + _paintedProps.n=0; + _colors.n=0; +} +//***************************************************************************************** +EntitiesArray* CartoBase::filter(EntitiesArray* dst, FilterEntities* filter) +{ + CartoBaseInfoEntity e = get(0); + while(e.isValid()) + { + if(filter->IsSeletedEntity(&e)) + { + if(!((*dst)+e)) + return 0; + } + e = e.next(); + } + return dst; +} +//***************************************************************************************** +bool CartoBase::remove(int i) +{ + if(i<_entities.n) + { + _entities[i].flagsInt |= CARTOBASE_DELETED_ENTITY; + if(iaEx) + iaEx->IaRemove(_entities[i].ref); + return true; + } + return false; +} +//***************************************************************************************** +bool CartoBase::removeRef(int r) +{ + return remove(refIndex[r]); +} +//***************************************************************************************** +bool CartoBase::clear() +{ + return false;//no funciona + //verifica entidades + int ind =0; + std::map indsl; + int il,ip,ic, id; + std::map indsp; + std::map indsc; + std::map indsd;//indices de pintado + il = ip=ic=id = 0; + //borra entidades marcadas + for(int i =0; i<_entities.n; i++) + { + if(_entities[i].flagsInt & CARTOBASE_DELETED_ENTITY) + continue; + if(i == ind) + { + ind++; + continue; + } + _entities[ind++]=_entities[i]; + } + + + //si borrados + if(ind == _entities.n) + goto ajus_mem; + + //verifica + _entities.n = ind; + for(int i =0; i<_entities.n; i++) + { + int aux = _entities[i].idPaintp; + //revisa propiedades de pintado + if(indsd.find(aux) == indsd.end()) + { + indsd[aux] = id++; + //revisa color + if(indsc.find(_paintedProps[i].color) == indsc.end()) + indsc[_paintedProps[i].color] =ic++; + _paintedProps[i].color = indsc[_paintedProps[i].color]; + } + _entities[i].idPaintp = indsd[aux]; + //segun tipo de entidad + aux =_entities[i].id; + switch(_entities[i].type) + { + case(CartoBaseTypes::Point): + { + if(indsp.find(aux) == indsp.end()) + indsp[aux] = ip++; + _entities[i].id = indsp[aux]; + break; + } + case(CartoBaseTypes::Line): + { + if(indsl.find(aux) == indsl.end()) + { + indsl[aux] = il++; + } + + int nn = _lines[aux].n; + aux= _lines[aux].ini; + + for(int ii =0; ii::iterator + iid = indsp.begin(); + iid != indsp.end(); + ++iid) + { + if(iid->second ==iid->first) + continue; + _points[iid->second] = _points[iid->first]; + } + _points.n=(int)indsp.size(); + for (std::map::iterator + iid = indsl.begin(); + iid != indsl.end(); + ++iid) + { + if(iid->second ==iid->first) + continue; + _lines[iid->second] = _lines[iid->first]; + } + _lines.n=(int)indsl.size(); + for (std::map::iterator + iid = indsd.begin(); + iid != indsd.end(); + ++iid) + { + if(iid->second ==iid->first) + continue; + _paintedProps[iid->second] = _paintedProps[iid->first]; + } + _paintedProps.n=(int)indsd.size(); + for (std::map::iterator + iid = indsc.begin(); + iid != indsc.end(); + ++iid) + { + if(iid->second ==iid->first) + continue; + _colors[iid->second] = _colors[iid->first]; + } + _colors.n=(int)indsc.size(); + +ajus_mem: + //ajusta memoria + if(!_entities.ajusta_mem()) + return false; + if(!_points.ajusta_mem()) + return false; + if(!_lines.ajusta_mem()) + return false; + if(!_paintedProps.ajusta_mem()) + return false; + if(!_colors.ajusta_mem()) + return false; + indexRef(); + return true; +} +//***************************************************************************************** +bool CartoBase::FastClear() +{ + //verifica entidades + + int ind =0; + //borra entidades marcadas + for(int i =0; i<_entities.n; i++) + { + if(_entities[i].flagsInt & CARTOBASE_DELETED_ENTITY) + continue; + if(i == ind) + { + ind++; + continue; + } + _entities[ind++]=_entities[i]; + } + _entities.n =ind; + reIndexRef(); + return true; +} +//***************************************************************************************** +bool CartoBase::MemClear() +{ + if(!FastClear()) + return false; + int npts =0; + int nlin=0; + //cuenta tipos de entidades----------- + for(int i =0; i< _entities.n; i++) + { + switch(_entities[i].type) + { + case(CartoBaseTypes::Point): + npts++; + break; + case(CartoBaseTypes::Line): + + nlin++; + npts+=_lines[_entities[i].id].n; + break;; + default: + break; + } + } + + for(int i =0; i<_paintedProps.n; i++) + _paintedProps[i].flags &= ~0x1; + for(int i =0; i<_colors.n; i++) + _colors[i].flags &= ~0x1; + Cgarray points;//coordenadas + Cgarray lines;//lineas + Cgarray paintedProps;//propiedades de pintado + Cgarray colors; + //pide memoria para arrays auxiliares + + if(!(points+=npts)) + return false; + if(!(lines+=nlin)) + return false; + for(int i =0; i<_entities.n; i++) + { + CartoBaseInfoEntity e =get(i); + + switch(e.entity()->type) + { + case(CartoBaseTypes::Point): + points+ *e.pto(); + e.entity()->id = points.n-1; + break; + case(CartoBaseTypes::Line): + lines+*e.line(); + lines[lines.n-1].ini = points.n; + for(int jj =0; jjn; jj++) + points+ e.pto()[jj]; + e.entity()->id = lines.n-1; + break; + default: + break; + } + //revisa propiedades de pintado + if(e.paintp()->flags & 0x1) + { + e.entity()->idPaintp = e.paintp()->color; + continue; + } + + paintedProps+*e.paintp(); + //revisa color + + if(e.color()->flags & 0x1) + { + paintedProps[paintedProps.n-1].color = e.color()->color; + } + else + { + paintedProps[paintedProps.n-1].color = colors.n; + colors+*e.color(); + e.color()->flags |=0x1 ; + e.color()->color = colors.n-1; + } + e.paintp()->flags |= 0x1; + e.entity()->idPaintp = paintedProps.n; + } + + if(_colors.ptr) + free(_colors.ptr); + _colors = colors; + colors.ptr = NULL; + + if(_lines.ptr) + free(_lines.ptr); + _lines = lines; + lines.ptr = NULL; + + if(_paintedProps.ptr) + free(_paintedProps.ptr); + _paintedProps = paintedProps; + paintedProps.ptr = NULL; + + if(_points.ptr) + free(_points.ptr); + _points = points; + points.ptr = NULL; + + //ajusta memoria + if(!_entities.ajusta_mem()) + return false; + if(!_points.ajusta_mem()) + return false; + if(!_lines.ajusta_mem()) + return false; + if(!_paintedProps.ajusta_mem()) + return false; + if(!_colors.ajusta_mem()) + return false; + + return true; +} +//***************************************************************************************** +bool CartoBase::importShp(char* path) +{ + CartoBaseShpManager shp; + Cb_file f; + char patdbf[256]; + if(!f.abre(path,1,0,1)) + return false; + shp.set(this); + int oldia =typeIA ; + typeIA = NIa; + if(!shp.ImportShp(&f)) + { + typeIA = oldia; + return false; + } + typeIA = oldia; + if(typeIA== NIa || typeIA == IntIa) + return true; + CartoBaseDBFManager dbf; + return dbf.leer(Cdir_manager::cambia_extension_archivo(path,patdbf,"dbf"),this); +} +//***************************************************************************************** +bool CartoBase::exportShp(char* path) +{ + return fexportShp(path); +} +//***************************************************************************************** +bool CartoBase::ptosExportShp(char* path) +{ + return fexportShp(path, CartoBaseTypes::Point); +} +//***************************************************************************************** +bool CartoBase::linesExportShp(char* path) +{ + return fexportShp(path, CartoBaseTypes::Line); +} +//***************************************************************************************** +bool CartoBase::fexportShp(char* path, int type) +{ + char patdbf[256]; + + CartoBaseShpManager shp; + + Cb_file f; + Cb_file fshx; + + if(!f.abre(path,2,1)) + return false; + if(!fshx.abre(Cdir_manager::cambia_extension_archivo(path,patdbf,"shx"),2,1)) + return false; + + if(!shp.ExportShp(&f,&fshx,this, type)) + return false; + if(typeIA== NIa) + return true; + CartoBaseDBFManager dbf; + FiterCartoBase enti; + if(type == CartoBaseTypes::Ndef) + type = _entities[0].type; + for(int i =0; i<_entities.n; i++) + { + if(_entities[i].type == type) + enti.ind+i; + + } + enti.cb = this; + return dbf.grabar(Cdir_manager::cambia_extension_archivo(path,patdbf,"dbf"), this,&enti); + //exporta dbf; +} +//***************************************************************************************** +void CartoBase::iniIndexRef() +{ + refIndex.clear(); + for(int i=0; i<_entities.n; i++) + { + _entities[i].ref=i; + refIndex[i]=i; + } + ref = _entities.n; +} +//***************************************************************************************** +void CartoBase::reIndexRef() +{ + refIndex.clear(); + for(int i=0; i<_entities.n; i++) + { + refIndex[_entities[i].ref]=i; + } +} +//***************************************************************************************** +void CartoBase::indexRef(bool buscaRepes) +{ + refIndex.clear(); + int ref_max=-1; + int r; + bool repes =false; + //busca maximo u si hay repes + for(int i=0; i<_entities.n; i++) + { + r =_entities[i].ref; + refIndex[r]=i; + if(r>ref_max) + ref_max = r; + } + if(ref<= ref_max) + ref = ref_max; + if(!buscaRepes) + return; + + for(int i=0; i<_entities.n; i++) + { + r =_entities[i].ref; + if(refIndex[r]!= i) + { + //referencias repetidas + _entities[i].ref =ref; + refIndex[ref] = i; + ref++; + } + } +} +//***************************************************************************************** +void* CartoBase::getIa( int refEnt ) +{ + if(iaEx) + return iaEx->IaGet(refEnt); + return NULL; +} +//***************************************************************************************** +void CartoBase::setExIa( DataIaCartoBase* ia ) +{ + typeIA = ExIa; + iaEx=ia; + iaEx->CBSet(this); + //añade a ia entidades existentes + for (int i =0; i<_entities.n; i++) + { + if(_entities[i].flagsInt & CARTOBASE_DELETED_ENTITY) + continue; + iaEx->IaAdd((_entities[i].ref)); + } +} +//***************************************************************************************** +bool CartoBase::IaGetSize( int *ncolm ) +{ + *ncolm =1; + return true; +} +//***************************************************************************************** +bool CartoBase::IaGetColm( int icol, char* name, BYTE *type, int *size, int*ndecimal ) +{ + if(icol!=0) + return false; + *size = 10; + *ndecimal=0; + *type = DBF_TYPE_DATA_I; + strcpy(name,iaName); + return true; +} +//***************************************************************************************** +bool CartoBase::IaGetVal( int refEnt, int icol, int* v ) +{ + if(icol!=0) + return false; + *v =getRef(refEnt).entity()->ia; + return true; +} +//***************************************************************************************** +void CartoBase::setNameIa( char *name ) +{ + strcpy(iaName, name); +} +//***************************************************************************************** + +CartoBaseInfoEntity FiterCartoBase::getEntity( int i ) +{ + return cb->get(ind[i]); +} +//***************************************************************************************** +int FiterCartoBase::getNumberEntities() +{ + return ind.n; +} +//***************************************************************************************** \ No newline at end of file diff --git a/CartoBase.h b/CartoBase.h new file mode 100644 index 0000000..f5311a7 --- /dev/null +++ b/CartoBase.h @@ -0,0 +1,134 @@ +#pragma once +#ifndef CartoBase_h +#define CartoBase_h + +#include "base_head.h" +#include "CartoBaseDef.h" +#include "CartoBaseElements.h" +#include "CartoElements.h" +#include "IaDataTable.h" +#include +/* +hacer el memoryclear +guardar dbf ia +*/ +class Cb_file; +class UTILES_EXPORT CartoBase: public SetEntities, public SetPtsR, public DataIaCartoBase +{ + //clases amigo----------------- + friend class CartoBaseInfoEntity; + friend class CartoBaseInfoPto; + friend class CartoBaseInfoLine; + friend class CartoBaseInfoBuilder; + friend class CartoPto; + friend class CartoLine; +private: + //info interna------------------------------- + int ref;//referencia para el siguiente elemento + CartoBasePaintedProps _defaultpaintedProps; + CartoBaseColor _defaultColor; + //array de informacion de entidades + Cgarray _entities;//entidades + Cgarray _points;//coordenadas + Cgarray _lines;//lineas + Cgarray _paintedProps;//propiedades de pintado + Cgarray _colors; + std::map refIndex;//indexado por referencias; + //datos de ia----------------------------------------- + char iaName[12];//nombre columna ia tipo IntIa + int typeIA;//indica el tipo de informacion asociada que se utilizara +public: + + IaDataTable dataIa; + DataIaCartoBase *iaEx; + enum TypedataIa + { + NIa=0,//sin informacion asociada + IntIa,//usa solo un entero por entidad como ia con nombre de columna iaName + DtIa,//usa la dataIa para almacenar info asociada + ExIa//informacion asociada externa + }; + + CartoBase(void); + ~CartoBase(void); + + //funciones----------------------------------------------------------------- + CartoBaseInfoEntity get(int i);//acceso a entidad iesima (modo lectura) + CartoBaseInfoEntity getRef(int r);//acceso a entidad con referencia r (modo lectura) + + + //añade elementos + bool add(CartoEntity& element); + bool add(CartoBase& cad); + + bool remove(int i);//pone marca de flag de borrado (pero sigue siendo accesible) + bool removeRef(int r); + + bool FastClear();//solo borra entidades y rehace las referencias + bool clear();//limpia elementos borrados y ajusta memoria + bool MemClear();//limpia memoria de todos los arrays + + EntitiesArray* filter(EntitiesArray* dst, FilterEntities *filter); + + virtual bool leer(char *path); + virtual bool grabar(char *path); + virtual bool leer(Cb_file *f); + virtual bool grabar(Cb_file *f); + + int addDefaultPaintedProps();//crea unas propiedades de pintado como las por defecto + + bool importShp(char* path);//importa shp + bool exportShp(char* path);//exporta a shp (todos los tipos que cuinciden con la primera) + bool ptosExportShp(char* path); + bool linesExportShp(char* path); + + void del();//limpia toda la carto (sin liberar memoria) + + //funciones de ia------------------------------------------------------------------- + void* getIa(int refEnt);//devuelve informacion asociada externa de la entidad refEnt + int getTypeIA(){return typeIA;}//devuelve el tipo de ia que tiene actualmente + void setExIa(DataIaCartoBase* ia);//setea un ia externo + int getEntityRef(int ientity);//devuelve la referencia + void setNameIa(char *name);//pone el nombre de la col + + //funciones por ser SetEntities + virtual CartoBaseInfoEntity getEntity(int i); + virtual int getNumberEntities(); + //funciones por ser SetPts + virtual double* getPto(int i); + virtual int getNumberPtos(); + //funciones auxiliares------------ + int getNexRef(){return ref;}; + + //funciones DataIaCartoBase + virtual bool IaGetSize( int *ncolm ); + virtual bool IaGetColm( int icol, char* name, BYTE *type, int *size, int*ndecimal ); + virtual bool IaGetVal( int refEnt, int icol, int* v ); + virtual bool IaFinW(){return true;} + +private: + + int add(CartoBaseEntity* src); + int add(CartoBasePoint* src); + int add(CartoBaseLine* src); + int add(CartoBasePaintedProps* src); + int add(CartoBaseColor* src); + + bool fexportShp(char* path, int type = CartoBaseTypes::Ndef); + + void indexRef(bool buscaRepes=false);//indexa referencias + void iniIndexRef();//crea indexado + void reIndexRef(); +}; + +class FiterCartoBase: public SetEntities +{ +public: + CartoBase* cb; + Cgarray ind; + + virtual CartoBaseInfoEntity getEntity( int i ); + + virtual int getNumberEntities(); +}; +#endif \ No newline at end of file diff --git a/CartoBaseDBFManager.cpp b/CartoBaseDBFManager.cpp new file mode 100644 index 0000000..39e176e --- /dev/null +++ b/CartoBaseDBFManager.cpp @@ -0,0 +1,165 @@ +#include "StdAfx.h" +#include "CartoBaseDBFManager.h" + +#include "ManagerDbfGdataTable.h" +//#include "CartoBaseElements.h" +//*************************************************************************** +CartoBaseDBFManager::CartoBaseDBFManager(void) +{ +} +//*************************************************************************** +CartoBaseDBFManager::~CartoBaseDBFManager(void) +{ +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfSet( int nrow, int ncolm ) +{ + _icol = 0; + _nncol = ncolm; + _oldRef = cb->getNexRef()-nrow; + return cb->iaEx->IaSet(nrow, ncolm); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfSetColm( char* name, BYTE type, int size ) +{ + bool res =cb->iaEx->IaSetColm(_icol++,name, type, size); + if(res && _nncol<=_icol) + cb->iaEx->IaAdd(_oldRef); + return res; +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfaddVal( int icol, int v ) +{ + return cb->iaEx->IaAddVal(_oldRef, icol, v); + +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfaddVal( int icol, double v ) +{ + return cb->iaEx->IaAddVal(_oldRef, icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfaddVal( int icol, __int64 v ) +{ + return cb->iaEx->IaAddVal(_oldRef, icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfaddVal( int icol, char* v ) +{ + return cb->iaEx->IaAddVal(_oldRef, icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfaddVal( int icol, void* v ) +{ + return cb->iaEx->IaAddVal(_oldRef, icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfFinRow() +{ + bool res = cb->iaEx->IaFinRow(_oldRef); + + _oldRef++; + if(cb->getNexRef()>_oldRef) + cb->iaEx->IaAdd(_oldRef); + return res; +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfFinR() +{ + return cb->iaEx->IaFinR(); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfGet( int *nrow, int *ncolm ) +{ + rowE =-1; + _nnrow =0; + *nrow=setEnt->getNumberEntities(); + return ia->IaGetSize(ncolm); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfGetColm( int icol, char* name, BYTE *type, int *size, int*ndecimal ) +{ + return ia->IaGetColm(icol,name,type,size,ndecimal); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfGetVal( int irow, int icol, int* v ) +{ + if(rowE!= irow) + { + e = setEnt->getEntity(irow); + rowE = irow; + } + + return ia->IaGetVal(e.entity()->ref,icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfGetVal( int irow, int icol, double* v ) +{ + if(rowE!= irow) + { + e = setEnt->getEntity(irow); + rowE = irow; + } + return ia->IaGetVal(e.entity()->ref ,icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfGetVal( int irow, int icol, __int64* v ) +{ + if(rowE!= irow) + { + e = setEnt->getEntity(irow); + rowE = irow; + } + + return ia->IaGetVal(e.entity()->ref, icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfGetVal( int irow, int icol, char** v ) +{ + if(rowE!= irow) + { + e = setEnt->getEntity(irow); + rowE = irow; + } + return ia->IaGetVal(e.entity()->ref,icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfGetVal( int irow, int icol, void** v ) +{ + if(rowE!= irow) + { + e = setEnt->getEntity(irow); + rowE = irow; + } + return ia->IaGetVal(e.entity()->ref,icol, v); +} +//*************************************************************************** +bool CartoBaseDBFManager::DbfFinW() +{ + return ia->IaFinW(); +} +//*************************************************************************** +bool CartoBaseDBFManager::leer( char *path, CartoBase*cartb ) +{ + cb = cartb; + switch(cb->getTypeIA()) + { + case(CartoBase::DtIa): + case (CartoBase::ExIa): + return ManagerDbf::leer(path,this); + case(CartoBase::NIa): + case(CartoBase::IntIa): + default: + return true; + } +} +//*************************************************************************** +bool CartoBaseDBFManager::grabar( char *path, DataIaCartoBase* iawx, SetEntities* s ) +{ + setEnt =s; + rowE =-1; + ia = iawx; + + return ManagerDbf::grabar(path,this); +} +//*************************************************************************** \ No newline at end of file diff --git a/CartoBaseDBFManager.h b/CartoBaseDBFManager.h new file mode 100644 index 0000000..44f616c --- /dev/null +++ b/CartoBaseDBFManager.h @@ -0,0 +1,49 @@ +#pragma once +#include "base_head.h" +#include "Fdbf.h" +#include "CartoBase.h" + +//clase helper para imporacion de un dbf a informacion asociada de cartobase +class UTILES_EXPORT CartoBaseDBFManager: public ListenerDbf_W, public ListenerDbf_R +{ + CartoBase *cb; + int _oldRef; + int _icol; + int _nncol; + int _nnrow; + CartoBaseInfoEntity e; + int rowE; + SetEntities *setEnt; + DataIaCartoBase* ia; +public: + + CartoBaseDBFManager(void); + ~CartoBaseDBFManager(void); + virtual bool leer(char *path, CartoBase*cartb); + virtual bool grabar(char *path, DataIaCartoBase* iawx, SetEntities* s); + + + //funciones auxiliares----------------------------------- + //funciones de lectura de shp-------------------------- + virtual bool DbfSet( int nrow, int ncolm ); + virtual bool DbfSetColm( char* name, BYTE type, int size ); + virtual bool DbfaddVal( int icol, int v ); + virtual bool DbfaddVal( int icol, double v ); + virtual bool DbfaddVal( int icol, __int64 v ); + virtual bool DbfaddVal( int icol, char* v ); + virtual bool DbfaddVal( int icol, void* v ); + virtual bool DbfFinRow(); + virtual bool DbfFinR(); + + //funciones de escritura de dbf----------------------- + virtual bool DbfGet( int *nrow, int *ncolm); + virtual bool DbfGetColm( int icol, char* name, BYTE *type, int *size, int*ndecimal ); + virtual bool DbfGetVal( int irow, int icol, int* v ); + virtual bool DbfGetVal( int irow, int icol, double* v ); + virtual bool DbfGetVal( int irow, int icol, __int64* v ); + virtual bool DbfGetVal( int irow, int icol, char** v ); + virtual bool DbfGetVal( int irow, int icol, void** v ); + virtual bool DbfFinW(); + + +}; diff --git a/CartoBaseDef.h b/CartoBaseDef.h new file mode 100644 index 0000000..1358893 --- /dev/null +++ b/CartoBaseDef.h @@ -0,0 +1,75 @@ +#pragma once +#ifndef CartoBaseDef_H +#define CartoBaseDef_H +#include "base_head.h" + +namespace CartoBaseTypes{ + enum { + Ndef = 0, + Point, + Line + }; +}; + +//calse coleccion de puntos (double[3]) solo lectura +class UTILES_EXPORT SetPtsR +{ +public: + virtual double* getPto(int i)=0;//devuelve el punto iesimo + virtual int getNumberPtos()=0;//devuelve numero de puntos totales +}; +//coleccion de puntos al que se le puede añadir mas +class UTILES_EXPORT SetPtsW +{ +public: + virtual bool addPto(double* p)=0;//añade el punto p al conjunto +}; +//constructor de setPtsW +class UTILES_EXPORT SetPtsWBuilder +{ +public: + virtual SetPtsW *build()=0;//devuelve una nueva clase SetPtsW +}; +class CartoBase; +//interface de ia +class UTILES_EXPORT DataIaCartoBase +{ +public: + virtual void* IaGet(int refEnt){return NULL;} + + virtual void CBSet(CartoBase* cb){} + virtual void IaRemove(int refEnt){} + virtual void IaRemoveAll(){} + virtual void IaAdd(int refEnt){} + + //informa del numero de filas y columnas que tiene la ia + virtual bool IaSet(int nrow, int ncolm){return true;} + virtual bool IaSetColm(int icol, char* name, BYTE type, int size){return true;} + virtual bool IaAddVal(int refEnt, int icol, int v){return true;} + virtual bool IaAddVal(int refEnt, int icol, double v){return true;} + virtual bool IaAddVal(int refEnt, int icol, __int64 v){return true;} + virtual bool IaAddVal(int refEnt, int icol, char* v){return true;} + virtual bool IaAddVal(int refEnt, int icol, void* v){return true;} + virtual bool IaFinRow(int refEnt){return true;} + virtual bool IaFinR(){return true;} + + + virtual bool IaGetSize( int *ncolm ){return false;} + virtual bool IaGetColm( int icol, char* name, BYTE *type, int *size, int*ndecimal ){return false;} + virtual bool IaGetVal( int refEnt, int icol, int* v ){return false;} + virtual bool IaGetVal( int refEnt, int icol, double* v ){return false;} + virtual bool IaGetVal( int refEnt, int icol, __int64* v ){return false;} + virtual bool IaGetVal( int refEnt, int icol, char** v ){return false;} + virtual bool IaGetVal( int refEnt, int icol, void** v ){return false;} + virtual bool IaFinW(){return true;} +}; + +#define TYPE_FILE "CartoBase" +#define VERSION_CART_BASE 100 +//falgs de entidades-------------- +#define CARTOBASE_DELETED_ENTITY 0x01 + + + +#endif + diff --git a/CartoBaseElements.cpp b/CartoBaseElements.cpp new file mode 100644 index 0000000..b44ab8d --- /dev/null +++ b/CartoBaseElements.cpp @@ -0,0 +1,298 @@ +#include "StdAfx.h" +#include "CartoBaseElements.h" +#include "CartoBase.h" +#include "CartoBaseShpManager.h" +#include "GeometryFunction.h" +#include "dir_manager.h" +//***************************************************************************************** +CartoBaseInfoEntity::CartoBaseInfoEntity() +{ + i_entity = -1; + ptr = 0; +} +//***************************************************************************************** +bool CartoBaseInfoEntity::isValid() +{ + return ptr && i_entity >= 0 && ptr->_entities.n > i_entity; +} +//***************************************************************************************** +CartoBaseInfoEntity CartoBaseInfoEntity::next() +{ + if(!isValid()) + return CartoBaseInfoEntity(); + return ptr->get(i_entity+1); +} +//***************************************************************************************** +CartoBasePoint* CartoBaseInfoEntity::pto() +{ + if(!fpto) + return 0; + return fpto(this); +} +//***************************************************************************************** +CartoBaseLine* CartoBaseInfoEntity::line() +{ + if(!fline) + return 0; + return fline(this); +} +//***************************************************************************************** +CartoBaseInfoEntity CartoBaseInfoEntity::prev() +{ + if(!isValid()) + return CartoBaseInfoEntity(); + return ptr->get(i_entity-1); +} +//***************************************************************************************** +CartoBaseEntity* CartoBaseInfoEntity::entity() +{ + if(!isValid()) + return NULL; + return ptr->_entities.get(i_entity); +} +//***************************************************************************************** +CartoBasePaintedProps* CartoBaseInfoEntity::paintp() +{ + CartoBaseEntity* e = CartoBaseInfoEntity::entity(); + if(e) + return ptr->_paintedProps.get(e->idPaintp); + return NULL; +} +//***************************************************************************************** +int CartoBaseInfoEntity::getNumberPtos() +{ + CartoBaseLine* l = line(); + if(!l)//es un punto + return 1; + return l->n; +} +//***************************************************************************************** +double* CartoBaseInfoEntity::getPto(int i) +{ + CartoBasePoint* aux =pto(); + if(aux) + return aux[i].pts; + return 0; +} +//***************************************************************************************** +CartoBaseColor* CartoBaseInfoEntity::color() +{ + CartoBasePaintedProps* pp = paintp(); + if(pp) + return ptr->_colors.get(pp->color); + return NULL; +} +//***************************************************************************************** +CartoBasePoint* CartoBaseInfoPto::pto(CartoBaseInfoEntity* c) +{ + CartoBaseEntity* e = c->entity(); + if(e) + return c->ptr->_points.get(e->id); + return NULL; +} +//***************************************************************************************** +CartoBasePoint* CartoBaseInfoLine::pto(CartoBaseInfoEntity* c) +{ + CartoBaseLine* l = c->line(); + if(l) + return c->ptr->_points.get(l->ini); + return NULL; +} +//***************************************************************************************** +CartoBaseInfoEntity EntitiesArray::getEntity(int i) +{ + CartoBaseInfoEntity* e = get(i); + if(e) + return *e; + return CartoBaseInfoEntity(); +} +//***************************************************************************************** +EntitiesArray* EntitiesArray::filter(EntitiesArray* dst, FilterEntities* filter) +{ + + for(int i =0 ; iIsSeletedEntity(e)) + { + if(!((*dst)+(*e))) + return 0; + } + } + return dst; +} +//***************************************************************************************** +bool EntitiesArray::exportShp(char* path, int type) +{ + CartoBaseShpManager shp; + char nshp[256]; + Cb_file f; + Cb_file fshp; + if(!f.abre(path,2,1)) + return false; + if(!fshp.abre(Cdir_manager::cambia_extension_archivo(path,nshp,"shx"),2,1)) + return false; + return shp.ExportShp(&f,&fshp, this, type); +} +//***************************************************************************************** +int EntitiesArray::getNumberEntities() +{ + return n; +} +//***************************************************************************************** +int EntitiesArray::getNumberPtos() +{ + int count =0; + for(int i =0; igetNumberPtos(); + } + return count; +} +//***************************************************************************************** +double* EntitiesArray::getPto(int i) +{ + int count =0; + + for(int i =0; igetNumberPtos(); + if(i>=count) + i -=count; + else + return get(i)->getPto(i); + } + return 0; +} +//***************************************************************************************** +CartoEntity* CartoBaseInfoEntity::getCopy(CartoEntity *buf) +{ + CartoBaseEntity* e = entity(); + CartoEntity * buff = NULL; + if(!e) + return NULL; + if(!buf) + buf = buff = CartoBaseInfoBuilder::get(e->type); + if( buf->getType()!= e->type) + return NULL; + if(!buf->set(this)) + { + if(buff) + delete buff; + } + return buf; +} +//***************************************************************************************** +double CartoBaseInfoEntity::getLong() +{ + return GeometryFunction::LongLine2d(this); +} +//***************************************************************************************** +//la distancia media a una línea de longitud mayor que this, +//partiendo de this y calculando la distancia de puntos equidistantes l_avan a los puntos +//más cercanos de line2 +double CartoBaseInfoEntity::disMedLines(SetPtsR *line2, double l_avan, double *desv) +{ + return GeometryFunction::DisMedLines(this,line2,l_avan,desv); +} +//***************************************************************************************** +//la distancia media a una línea de longitud mayor que this, +//calculando la distancia de los puntos de this a line2 +double CartoBaseInfoEntity::disMedLines(SetPtsR *line2, double *desv) +{ + return GeometryFunction::DisMedLines(this,line2); +} +//***************************************************************************************** +double *CartoBaseInfoEntity::GetPtoDis(double dis, double *dst, double *distTot) +{ + return GeometryFunction::GetPto(this, dis, dst, distTot); +} +//***************************************************************************************** +double CartoBaseInfoEntity::DisPtoLine(double*p, int* idpto, double *lamb) +{ + return GeometryFunction::DisPtoLine(this,p,idpto,lamb); +} +//***************************************************************************************** +double CartoBaseInfoEntity::DplineSeg(double* s1, double *s2,int *n, double *lamd1,double *lamb2) +{ + return GeometryFunction::DplineSeg(this,s1, s2,n, lamd1,lamb2); +} +//***************************************************************************************** +SetPtsW *CartoBaseInfoEntity::GetNPrimePtos(SetPtsW *ldst, int nptos, double dis, BOOL avanza) +{ + return GeometryFunction::GetNPrimePtos(this,ldst,nptos,dis,avanza); +} +//***************************************************************************************** +double *CartoBaseInfoEntity::PtInLine(int ip, double lamb, double *pp ) +{ + return GeometryFunction::PtInLine( this, ip, lamb , pp ); +} +//***************************************************************************************** +bool CartoBaseInfoEntity::DivLine( SetPtsW* ldst1, SetPtsW* ldst2, int ip, double lamb ) +{ + double dis=GeometryFunction::DisInLine(this,ip,lamb); + if(dis<0) + return false; + return GeometryFunction::DivLine(this,ldst1,ldst2,dis); +} +//***************************************************************************************** +void* CartoBaseInfoEntity::getIa() +{ + CartoBaseEntity* e = entity(); + if(e) + return ptr->getIa(e->ref); + return NULL; +} + +//***************************************************************************************** +CartoBaseLine* CartoBaseInfoLine::line(CartoBaseInfoEntity* c) +{ + CartoBaseEntity* e = c->entity(); + if(e) + return c->ptr->_lines.get(e->id); + return NULL; +} +//***************************************************************************************** +CartoBaseInfoEntity CartoBaseInfoBuilder::get(int i, CartoBase* ptr) +{ + CartoBaseInfoEntity res; + if(!ptr) + goto mal; + if(i<0 || ptr->_entities.n<= i) + goto mal; + res.ptr = ptr; + res.i_entity = i; + switch(ptr->_entities[i].type) + { + case (CartoBaseTypes::Point): + { + res.fline= 0; + res.fpto= CartoBaseInfoPto::pto; + break; + } + case (CartoBaseTypes::Line): + { + res.fline= CartoBaseInfoLine::line; + res.fpto= CartoBaseInfoLine::pto; + break; + } + default: + break; + } +mal: + return res; +} +//***************************************************************************************** +CartoEntity* CartoBaseInfoBuilder::get(int type) +{ + + switch(type) + { + case (CartoBaseTypes::Point): + return new CartoPto(); + case (CartoBaseTypes::Line): + return new CartoLine(); + } + return NULL; +} +//***************************************************************************************** \ No newline at end of file diff --git a/CartoBaseElements.h b/CartoBaseElements.h new file mode 100644 index 0000000..eab9336 --- /dev/null +++ b/CartoBaseElements.h @@ -0,0 +1,172 @@ +#pragma once +#include "base_head.h" +#include "cartoBaseDef.h" +#include "garray.h" +#ifndef CartoBaseElements_H +#define CartoBaseElements_H +class CartoEntity; +//clases internas de cartobase---------------------------------------------- +class UTILES_EXPORT CartoBaseEntity +{ +public: + int id; //indice a objeto + int type; //tipo de entidad + int idPaintp; //inide a propiedades + int flagsUser; //flags para uso de usuario + int flagsInt; //flags para uso interno + int ref; //referencia unica por elemento + + //tamaño--------- + int mima[2]; //indice a punto maximo y minimo (el elemento esta contenido entre dichos puntos) + int ia; //indice a informacion adicional + + CartoBaseEntity() + { + id = -1; + idPaintp = -1; + flagsInt = 0; + } +}; +//entidad interna de putno +class UTILES_EXPORT CartoBasePoint +{ +public: + double pts[3];//coordenadas del punto + + CartoBasePoint(){ + pts[0]=pts[1]=pts[2]=0; + } +}; + +//entidad interna de linea +class UTILES_EXPORT CartoBaseLine +{ +public: + int ini; //inidce a punto inicio + int n; //numero de puntos del lineal + CartoBaseLine() + { + n = 0; + ini = -1; + } +}; +//entidad interna de propiedades de pintado +class UTILES_EXPORT CartoBasePaintedProps +{ +public: + int color; //indice a color + int peso; //grosor o tamaño de letra (segun entidad) + int prioridad; //prioridad de pintado + int flags; //flags internos 0x1 (visto para los clear) + CartoBasePaintedProps() + { + color = -1; + peso = 1; + flags = 0; + } +}; +//entidad interna de color +class UTILES_EXPORT CartoBaseColor +{ +public: + + int color; + int flags; //flags internos 0x1 (visto para los clear) + CartoBaseColor() + { + color = 0; + flags = 0; + } +}; + +//entidad base de informacion +class CartoBase; +class UTILES_EXPORT CartoBaseInfoEntity: public SetPtsR +{ +public: + //funciones externas + CartoBasePoint* (*fpto)(CartoBaseInfoEntity *c); + CartoBaseLine* (*fline)(CartoBaseInfoEntity *c); + int i_entity; + + CartoBase* ptr; + + CartoBaseInfoEntity(); + + virtual bool isValid(); //dice si es valido o no la entidad de informacion + virtual CartoBaseInfoEntity next(); //devuelve entidad siguiente + virtual CartoBaseInfoEntity prev(); //devuelve entidad anterior + + //acceso a informacion interna + virtual CartoBasePoint* pto(); + virtual CartoBaseEntity* entity(); + virtual CartoBaseLine* line(); + virtual CartoBasePaintedProps* paintp(); + virtual CartoBaseColor* color(); + virtual CartoEntity* getCopy(CartoEntity *buf=NULL); + //funciones SetPts-------------------------- + virtual double* getPto(int i); + virtual int getNumberPtos(); + + void* getIa(); + double getLong(); + double disMedLines(SetPtsR *line2, double l_avan, double *desv=NULL); + double disMedLines(SetPtsR *line2, double *desv=NULL); + double DisPtoLine(double*p, int* idpto=NULL, double *lamb=NULL); + SetPtsW *GetNPrimePtos(SetPtsW *ldst, int nptos, double dis, BOOL avanza); + bool DivLine(SetPtsW* ldst1, SetPtsW* ldst2, int ip, double lamb); + double *GetPtoDis(double dis, double *dst, double *distTot); + double *PtInLine(int ip, double lamb, double *pp); + double DplineSeg(double* s1, double *s2,int *n=NULL, double *lamd1=NULL,double *lamb2=NULL); +}; +//calse coleccion de entidades +class UTILES_EXPORT SetEntities +{ +public: + virtual CartoBaseInfoEntity getEntity(int i)=0; + virtual int getNumberEntities()=0; +}; + +//clase de filtrado de entidades +class UTILES_EXPORT FilterEntities +{ +public: + virtual bool IsSeletedEntity(CartoBaseInfoEntity *e)=0; +}; + +//array de entidades +class UTILES_EXPORT EntitiesArray: public Cgarray, public SetEntities, public SetPtsR +{ +public: + virtual CartoBaseInfoEntity getEntity(int i); + virtual int getNumberEntities(); + + virtual double* getPto(int i); + virtual int getNumberPtos(); + + EntitiesArray* filter(EntitiesArray* dst, FilterEntities* filter); + bool exportShp(char* path, int type = CartoBaseTypes::Ndef); +}; +//entidad de informacion punto +class UTILES_EXPORT CartoBaseInfoPto +{ +public: + static CartoBasePoint* pto(CartoBaseInfoEntity*c); +}; +//entidad de informacion linea +class UTILES_EXPORT CartoBaseInfoLine +{ +public: + + static CartoBasePoint* pto(CartoBaseInfoEntity*c); + static CartoBaseLine* line(CartoBaseInfoEntity*c); +}; + +//clase constructor de entidades info +class UTILES_EXPORT CartoBaseInfoBuilder +{ +public: + static CartoBaseInfoEntity get(int i, CartoBase* ptr); + static CartoEntity* get(int type); +}; +#endif diff --git a/CartoBaseShpManager.cpp b/CartoBaseShpManager.cpp new file mode 100644 index 0000000..5bd37c5 --- /dev/null +++ b/CartoBaseShpManager.cpp @@ -0,0 +1,202 @@ +#include "StdAfx.h" +#include "CartoBaseShpManager.h" +#include "Fshape.h" +//************************************************************************** +CartoBaseShpManager::CartoBaseShpManager(void) +{ + cad = NULL; +} +//************************************************************************** +CartoBaseShpManager::~CartoBaseShpManager(void) +{ +} +bool CartoBaseShpManager::ExportShp(Cb_file *file, Cb_file*fshx, SetEntities *entities, int type) +{ + Fshape shp; + if(type == CartoBaseTypes::Ndef) + { + if(entities->getNumberEntities()>0) + type = entities->getEntity(0).entity()->type; + else + type=CartoBaseTypes::Line; + } + switch(type) + { + case(CartoBaseTypes::Point): + { + return ExportPts(file,fshx, entities); + } + case(CartoBaseTypes::Line): + { + return ExportLine(file,fshx, entities); + } + default: + return false; + + } + return true; +} +//************************************************************************** +bool CartoBaseShpManager::ImportShp(Cb_file *file) +{ + Fshape shp; + if(!shp.leeHead(file)) + return false; + switch(shp.getType()) + { + case(Fshape::Rpoint): + case(Fshape::RMpoint): + return ImportPoints(&shp); + break; + case(Fshape::RPolyLine): + return Importline(&shp); + break; + case(Fshape::Rpolygon): + return ImportPoligon(&shp); + break; + } + return false; +} +//************************************************************************** +bool CartoBaseShpManager::Importline(Fshape *shp) +{ + CartoLine lin; + lin.idPropsP = cad->addDefaultPaintedProps(); + double *pt; + //piner indice de color + while(shp->LeeRecord()) + { + int nn = shp->getNp(); + for(int p=0; pgetNPt(p); + if(np<=0) + continue; + if(!(lin.pts+=np)) + return false; + + lin.pts.n = np; + for(int i = 0; iget(p,i); + lin.pts[i][0]=pt[0]; + lin.pts[i][1]=pt[1]; + lin.pts[i][2]=0; + } + if(!cad->add(lin)) + return false; + } + } + return true; +} +//************************************************************************** +bool CartoBaseShpManager::ImportPoints(Fshape *shp) +{ + CartoPto pto; + pto.pt[2]=0; + pto.idPropsP = cad->addDefaultPaintedProps(); + + //piner indice de color + while(shp->LeeRecord()) + { + int i = 0; + double *p = shp->get(i++); + while(p) + { + pto.pt[0] = p[0]; + pto.pt[1] = p[1]; + if(!cad->add(pto)) + return false; + p = shp->get(i++); + } + } + return true; +} +//************************************************************************** +bool CartoBaseShpManager::ExportPts(Cb_file *file,Cb_file *fshx, SetEntities *entities) +{ + Fshape shp; + Cgarray pts; + int nn = 100; + if(nn>entities->getNumberEntities()) + nn = entities->getNumberEntities(); + if(!(pts+=(nn*2))) + return false;//sin memoria + + if(!shp.set(Fshape::Rpoint,2,file, fshx)) + return false; + int j =0; + pts.n = nn*2; + for(int i = 0; igetNumberEntities(); i++) + { + if(j == pts.n) + { + if(!shp.grabaRecord(&pts)) + return false; + j = 0; + } + CartoBaseInfoEntity ee =entities->getEntity(i); + if(ee.entity()->type != CartoBaseTypes::Point) + continue; + memcpy(&pts[j],ee.pto()->pts,sizeof(double)*2); + j+=2; + } + pts.n = j; + if(j>0 && !shp.grabaRecord(&pts)) + return false; + return shp.FinGraba(); +} +//************************************************************************** +bool CartoBaseShpManager::ExportLine(Cb_file *file,Cb_file *fshx, SetEntities *entities) +{ + Fshape shp; + Cgarray pts; + Cgarray parts; + CartoBaseLine *l; + int nn = 1; + if(nn>entities->getNumberEntities()) + nn = entities->getNumberEntities(); + if(!(parts+=nn)) + return false; + if(!shp.set(Fshape::RPolyLine, 2,file,fshx)) + return false; + int j =0; + parts.n = nn; + for(int i = 0; igetNumberEntities(); i++) + { + if(j >= parts.n) + { + if(!shp.grabaRecord(&pts, &parts)) + return false; + j = 0; + pts.n =0; + } + CartoBaseInfoEntity ee =entities->getEntity(i); + if(ee.entity()->type != CartoBaseTypes::Line) + continue; + l =ee.line(); + if(!l) + continue; + parts[j++] = pts.n; + + if(!(pts+=(l->n*2))) + return false; + CartoBasePoint *pp = entities->getEntity(i).pto(); + for(int p = 0; pn; p++) + { + pts.n=pts.n+2; + memcpy(&pts[pts.n-2],pp[p].pts,sizeof(double)*2); + } + } + parts.n = j; + if(j>0 && !shp.grabaRecord(&pts, &parts)) + return false; + return shp.FinGraba(); +} +//************************************************************************** +bool CartoBaseShpManager::ImportPoligon(Fshape *shp) +{ + return false; +} +//************************************************************************** diff --git a/CartoBaseShpManager.h b/CartoBaseShpManager.h new file mode 100644 index 0000000..53554de --- /dev/null +++ b/CartoBaseShpManager.h @@ -0,0 +1,28 @@ +#pragma once +#include "base_head.h" +#include "garray.h" +#include "CartoBase.h" + +class Cb_file; +class Fshape; +//clase helper para inportacion de shp a un carto base +class UTILES_EXPORT CartoBaseShpManager +{ + CartoBase* cad; + bool ImportPoints(Fshape *shp); + bool Importline(Fshape *shp); + bool ImportPoligon(Fshape *shp); + bool ExportLine(Cb_file *file, Cb_file *fshx, SetEntities *entities); + bool ExportPts(Cb_file *file, Cb_file *fshx, SetEntities *entities); + +public: + CartoBaseShpManager(void); + ~CartoBaseShpManager(void); + + void set(CartoBase* cb){cad = cb;} + + bool ImportShp(Cb_file *file); + + bool ExportShp(Cb_file *file,Cb_file *fshx, SetEntities *entities, int type = CartoBaseTypes::Ndef); + +}; diff --git a/CartoElements.cpp b/CartoElements.cpp new file mode 100644 index 0000000..f166591 --- /dev/null +++ b/CartoElements.cpp @@ -0,0 +1,195 @@ +#include "StdAfx.h" +#include "CartoBaseElements.h" +#include "CartoElements.h" +#include "CartoBase.h" +#include "GeometryFunction.h" +//***************************************************************************************** +CartoBaseEntity* CartoComun::get(CartoBaseEntity * dst) +{ + dst->flagsUser = flagsUser; + dst->ia=ia; + dst->type = getType(); + return dst; +} +//***************************************************************************************** +CartoBasePaintedProps* CartoComun::get(CartoBasePaintedProps * dst) +{ + dst->peso = peso; + return dst; +} +//***************************************************************************************** +CartoBaseColor* CartoComun::get(CartoBaseColor * dst) +{ + dst->color = color; + return dst; +} +//***************************************************************************************** +bool CartoComun::setInfo(CartoBaseInfoEntity * info) +{ + CartoBaseEntity *e =info->entity(); + CartoBaseColor *c =info->color(); + CartoBasePaintedProps *p =info->paintp(); + if(!e || !c || !p) + return false; + flagsUser = e->flagsUser; + color= c->color; + peso= p->peso; + id= e->id; + return true; +} +//***************************************************************************************** +CartoEntity* CartoPto::set(CartoBaseInfoEntity *src) +{ + if(!setInfo(src)) + return NULL; + CartoBasePoint *p = src->pto(); + if(!p) + return NULL; + memcpy(pt,p->pts,sizeof(double)*3); + return this; +} +//***************************************************************************************** +double* CartoPto::getPto(int i) +{ + if(i==0) + return pt; + return NULL; +} +//***************************************************************************************** +int CartoPto::CopyInTo(CartoBase *src) +{ + CartoBaseEntity e; + CartoBasePaintedProps p; + CartoBaseColor c; + CartoBasePoint pt; + memcpy(pt.pts, &this->pt, sizeof(double)*3); + e.id = src->add(&pt); + + if(idPropsP<0) + { + p.color = src->add(get(&c)); + if(p.color<0) + return -1; + e.idPaintp = src->add(get(&p)); + } + else + e.idPaintp = idPropsP; + + if(e.idPaintp<-1) + return -1; + if(e.id<-1) + return -1; + return src->add(get(&e)); +} +//***************************************************************************************** +double* CartoLine::getPto(int i) +{ + return pts[i]; +} +//***************************************************************************************** +double CartoLine::getLong() +{ + return GeometryFunction::LongLine2d(this); +} +//***************************************************************************************** +double *CartoLine::GetPtoDis(double dis, double *dst, double *distTot) +{ + return GeometryFunction::GetPto(this, dis, dst, distTot); +} +//***************************************************************************************** +bool CartoLine::addPto(double *p) +{ + if(!(pts+=1)) + return false; + pts.n++; + memcpy(pts[pts.n-1],p, sizeof(double)*3); + return true; + +} +//***************************************************************************************** +CartoEntity* CartoLine::set(CartoBaseInfoEntity *src) +{ + if(!setInfo(src)) + return NULL; + CartoBaseLine *l = src->line(); + if(!l) + return NULL; + pts.n = 0; + pts+=l->n; + pts.n = l->n; + CartoBasePoint *p = src->pto(); + for(int i =0 ; in; i++) + { + memcpy(pts.ptr[i],p->pts,sizeof(double)*3); + p=&p[1]; + } + return this; +} +//***************************************************************************************** +int CartoLine::CopyInTo(CartoBase *src) +{ + if(pts.n<=0) + return -1; + + CartoBaseEntity e; + CartoBasePaintedProps p; + CartoBaseColor c; + CartoBasePoint pt; + CartoBaseLine l; + + l.n= pts.n; + if(!(src->_lines+=pts.n)) + return -1; + memcpy(pt.pts,pts[0], sizeof(double)*3); + l.ini = src->add(&pt); + + for(int i = 1; iadd(&pt); + } + + if(idPropsP<0) + { + p.color = src->add(get(&c)); + if(p.color<0) + return -1; + e.idPaintp = src->add(get(&p)); + } + else + e.idPaintp = idPropsP; + + if(e.idPaintp<-1) + return -1; + e.id = src->add(&l); + if(e.id<-1) + return -1; + return src->add(get(&e)); +} +//***************************************************************************************** +void CartoLine::invert() +{ + int ini =0; + int fin =pts.n-1; + double d; + while(ini pts; + CartoLine(){}; + + virtual int getType()//devuelve tipo de entidad + { + return CartoBaseTypes::Line; + }; + + virtual CartoEntity* set(CartoBaseInfoEntity *src); + virtual int CopyInTo(CartoBase *src); + virtual int getNumberPtos(){return pts.n;} + virtual double* getPto(int i); + virtual bool addPto(double* p); + //funciones de geometria---------------------------------- + void invert();//invierte el sentido de los pts + double getLong(); + double *GetPtoDis(double dis, double *dst, double *distTot = NULL); +}; diff --git a/Csock_cl.cpp b/Csock_cl.cpp new file mode 100644 index 0000000..ee990b6 --- /dev/null +++ b/Csock_cl.cpp @@ -0,0 +1,339 @@ +#include "StdAfx.h" +#include "Csock_cl.h" +#include "utiles_dll.h" +#include "_error.h" +#include "utl.h" +//*********************************************************************************************** +Csock_cl::Csock_cl(BOOL*sal/*=NULL*/, C_error*e/*=NULL*/ ) +{ + creado = false; + buf=NULL; + nb=mb=0; + time_sleep=1; + intentos=500; + //creamos log error-------------- + if (e) + { + borra_er=FALSE; + er=e; + } + else + { + borra_er=TRUE; + er=new C_error(); + } + //ponemos pirate--------------- + if(sal) + { + pirate=sal; + borra_pirate=FALSE; + } + else + { + pirate=new BOOL(); + borra_pirate=TRUE; + } + +} + +//*********************************************************************************************** +Csock_cl::~Csock_cl(void) +{ + if (pirate&&borra_pirate) + free(pirate); + if (buf) + free(buf); + if (borra_er && er) + delete er; +} +//*********************************************************************************************** +BOOL Csock_cl::Create( UINT puerto, int tipo, long eventos ,LPCTSTR ip) +{ + //AFX_MANAGE_STATE(AfxGetStaticModuleState()); + Cutiles_dll dll; + BOOL resul=CAsyncSocket::Create(puerto, tipo,eventos,ip); + if (!resul) + { + er->pon_win(MODULO_CSOCK_CL); + } + else + creado =true; + return resul; +} +//*********************************************************************************************** +BOOL Csock_cl::conectar(char *ipdot,int puerto) +{ + Cutiles_dll dll; + //AFX_MANAGE_STATE(AfxGetStaticModuleState()); + fd_set rfds; + struct timeval tv; + FD_ZERO(&rfds); + FD_SET(this->m_hSocket, &rfds); + tv.tv_sec = 5; + tv.tv_usec = 0; + int err,vez; + CString cstr; + if(!creado && ! Create()) + return FALSE; + + if (Connect(ipdot, puerto)) + { + err = GetLastError(); + if(err != WSAEWOULDBLOCK) + { + er->pon_win(MODULO_CSOCK_CL); + return(FALSE); + } + } + + //vemos que realmente este conectado + vez = 0; + while (!*pirate) + { + int pruebaconexion = select((int)this->m_hSocket+1, NULL, &rfds, NULL, &tv); + if(pruebaconexion == 1) + break; + else if(pruebaconexion == SOCKET_ERROR && vez>20) + { + er->pon_win(MODULO_CSOCK_CL); + return FALSE; + } + vez++; + Sleep(time_sleep); + if (vez > intentos) + { + er->pon(MODULO_CSOCK_CL,"conectar:Demasiado tiempo esperando"); + return FALSE; + } + } + if(*pirate) + { + er->pon(MODULO_CSOCK_CL,"conectar: Solicitud de salida activado"); + return FALSE; + } + return TRUE; +} +//*********************************************************************************************** +BOOL Csock_cl::recibe_package(int indice) +{ + nb=indice;//bytes recibidos; + int bp=0;//bytes del bloque; + + //pillamos cabezera------------------------------------------------ + if (!recibe((BYTE*)&cab,sizeof(Package_head_0))) + return FALSE; + //verificamos------------------------------------------------------ + if(cab.version!=VERSION_PACKAGE_HEAD) + { + er->pon(MODULO_CSOCK_CL,"recibe_package:Versión de paquete recibido no compatible"); + return FALSE; + } + cuida_buf(cab.nb); + //miramos si es un paquete---------------------------------------- + if(cab.n==1) + { + if (!recibe((BYTE*)&buf[nb],cab.nb)) + return FALSE;//error al parte + nb+=cab.nb; + } + else + { + //pillamos partes--------------------------------------------- + for (int i=0; imb) + { + er->pon(MODULO_CSOCK_CL,"recibe_package:Paquete defectuoso, tamaño muy grande"); + return FALSE;//no entra en buffer + } + //pillamos parte------------------------ + if (!recibe((BYTE*)&buf[nb],bp)) + return FALSE;//error al parte + nb+=bp; + } + } + //verificamos----------------------------------------------------- + if(cab.nb!=nb-indice) + { + er->pon(MODULO_CSOCK_CL,"recibe_package:Paquete defectuoso, tamaño incorrecto"); + return FALSE;//no coinciden bytes + } + //desencriptamos si hace falta------------------------------------ + if (cab.flags & FLAG_PACKAGE_HEAD_0_ENCRIPT1) + { + Cutl::descifra1(&buf[indice],cab.nb); + } + return TRUE; +} +//*********************************************************************************************** +void Csock_cl::cuida_buf( int n ) +{ + if (nb+n>=mb) + { + //necesitamos memoria------------------------------------------ + mb+=n; + if (buf) + buf=(BYTE*)malloc(mb); + else + buf=(BYTE*)realloc(buf,mb); + } +} +//*********************************************************************************************** +BOOL Csock_cl::envia_package( BYTE* buff, int n,int encrip ) +{ + int env=0; + int en=0; + //rellenamos cabecera---------------------- + Package_head_0 cb; + cb.nb=n; + cb.flags=0; + if (encrip==1) + { + cb.flags=cb.flags | FLAG_PACKAGE_HEAD_0_ENCRIPT1; + Cutl::cifra1(buff,n); + } + + cb.version=VERSION_PACKAGE_HEAD; + + //calculamos bloques--------------------------------- + cb.n=(n/MAX_LONG_PACKAGE_0)+1; + cb.nb=n; + //enviamos cabecera---------------------------------- + if(!envia((BYTE *)&cb,sizeof(cb))) + { + return FALSE;//error al enviar cabecera + } + //enviamos en uno si se puede------------------------ + if (cb.n==1) + { + if (!envia(buff,cb.nb)) + { + return FALSE;//error al enviar paquete + } + env=cb.nb; + } + else + { + //enviamos en bloques----------------------------- + for (int i=0; iMAX_LONG_PACKAGE_0) + en=MAX_LONG_PACKAGE_0; + //enviamos numero----------------------------- + if (!envia((BYTE*)&en,sizeof(int))) + { + return FALSE;//error al tamaño + } + //enviamos datos------------------------------ + if (!envia(&buff[env],en)) + { + return FALSE;//error al enviar datos + } + env+=en; + } + } + if (*pirate) + { + er->pon(MODULO_CSOCK_CL,"envia_package: Solicitud de salida activado"); + return FALSE; + } + //verificamos---------------------------------------- + return env==n; +} +//*********************************************************************************************** +BOOL Csock_cl::recibe( BYTE*b, int n ) +{ + //int n,k,nv,err; + CString s; + int rec=0, rec_a=0,ier,nv=0;//bytes recibidos + + while (!*pirate && recpon_win(MODULO_CSOCK_CL); + return(FALSE); + } + nv++; + if (nv > intentos) + { + er->pon(MODULO_CSOCK_CL,"Recibe: Demasiado tiempo esperando"); + return FALSE; + } + Sleep(time_sleep); + } + else if (rec_a == 0) + { + er->pon(MODULO_CSOCK_CL,"Recibe: Socket desconectado"); + return(FALSE); + } + else + { + rec+=rec_a; + nv = 0; + } + + } + + if(*pirate) + { + er->pon(MODULO_CSOCK_CL,"Recibe: Solicitud de salida activado"); + return FALSE; + } + return TRUE; +} +//*********************************************************************************************** +BOOL Csock_cl::envia( BYTE*buff, int n) +{ + //int ns,nv,err,ib; + int nv=0,env=0,env_a=0,ier; + //nv = ib = 0; + + while (!*pirate && n>env) + { + //enviamos------------------------------------------- + env_a = Send(&buff[env],n-env,0); + + if(env_a <= 0) + { + //analizamos el fallo---------------------------- + ier = GetLastError(); + if (ier != WSAEWOULDBLOCK) + { + er->pon_win(MODULO_CSOCK_CL); + return(FALSE); + } + //toca esperar----------------------------------- + if (nv > intentos) + { + er->pon(MODULO_CSOCK_CL,"Envia: Demasiado tiempo esperando"); + return(FALSE); + } + nv++; + Sleep(time_sleep); + } + else + { + env+=env_a; + nv=0; + } + } + if(*pirate) + { + er->pon(MODULO_CSOCK_CL,"Envia: Solicitud de salida activado"); + return FALSE; + } + + return TRUE; +} +//*********************************************************************************************** \ No newline at end of file diff --git a/Csock_cl.h b/Csock_cl.h new file mode 100644 index 0000000..29fe83a --- /dev/null +++ b/Csock_cl.h @@ -0,0 +1,50 @@ +#if !defined(AFX_SOCK_SIMPLE_H__8491F9CB_65AF_44E1_80A3_52176804CD08__INCLUDED_) +#define AFX_SOCK_SIMPLE_H__8491F9CB_65AF_44E1_80A3_52176804CD08__INCLUDED_ + +#include +#include "utiles_def.h" +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +#endif +#define MODULO_CSOCK_CL "Csock_cl" +#include + +class C_error; +//socket cliente--------------------------------- +class UTILES_EXPORT Csock_cl : public CAsyncSocket +{ +public: + //variables---------------------------------- + BOOL *pirate; + BOOL borra_pirate; + BYTE *buf; + int mb,nb; + Package_head_0 cab; + C_error* er; + int time_sleep;//tiempo espera + int intentos; + bool creado; + //variables aux------------------------------ +private: + BOOL borra_er; + //cons--------------------------------------- +public: + Csock_cl(BOOL*sal=NULL,C_error*e=NULL); + virtual ~Csock_cl(void); + + //funciones---------------------------------- + BOOL Create( UINT puerto=0 , int tipo=SOCK_STREAM , + long evento=FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE , + LPCTSTR ip=NULL ); + + BOOL conectar(char *ipdot,int puerto);//conecta con un puerto y ip + + BOOL recibe_package(int indice);//recibe package y lo pone en buffer apartir de indice; + BOOL envia_package(BYTE* buff, int n, int encrip=0);//envia el buffer en packages si encrip=1 (hacemos encrip1) + //funciones auxiliares----------------------- + void cuida_buf(int n);//asegura en buf un espacio de n bytes; + BOOL recibe(BYTE*b, int n);//recive n bytes y lo pone en b; + BOOL envia(BYTE*buff, int n);//envia bytes sin mas; + +}; diff --git a/DataTransfer.cpp b/DataTransfer.cpp new file mode 100644 index 0000000..c1c6900 --- /dev/null +++ b/DataTransfer.cpp @@ -0,0 +1,336 @@ +#include "StdAfx.h" +#include "DataTransfer.h" +#include "Csock_cl.h" +//********************************************************************************** +DataTransfer::DataTransfer(void) +{ + nb_ini =0; + n_buf =0; + sizeBuf =0; + nb_total =0; + sc =NULL; + dt =NULL; + total_p =0; + sc_p =0; + dt_p =0; + cancela = false; + mode = MODE_RECEIVE; + thbuf.data = this; + thsoc.data = this; + + +} +//********************************************************************************** +DataTransfer::~DataTransfer(void) +{ + cancela = true; + thbuf.join(); + thsoc.join(); +} +//********************************************************************************** +bool DataTransfer::start() +{ + + if(currando() || !sc || !dt || nb_buf.n<=0 || buf.n<=0 || sizeBuf<=0) + return false; + errorSoc = 0; + errorDat =0; + nb_total =0; + total_p =0; + sc_p =0; + dt_p =0; + porcen =0; + mal = false; + cancela = false; + if(mode == MODE_SEND) + { + nb_total =dt->getNB_it(); + if(!dt->setPosition_it(nb_ini) || nb_total<=0) + return false; + nb_total = nb_total-nb_ini; + total_p = (int)(nb_total*1./sizeBuf); + if(nb_total>(total_p*sizeBuf)) + total_p++; + } + + if(!thbuf.lanza("DataTransferBuf")) + return false; + + if(!thsoc.lanza("DataTransferSoc")) + { + cancela = true; + thbuf.join(); + cancela = false; + return false; + } + return true; +} +//********************************************************************************** +bool DataTransfer::currando() +{ + return thsoc.isRunning() || thbuf.isRunning(); +} +//********************************************************************************** +bool DataTransfer::isCanceled() +{ + return cancela; +} +//********************************************************************************** +bool DataTransfer::setMode( int mod, int nbbuf /*= (1024*5)*/,int nbuf/*=2*/ ) +{ + mode = mod; + nb_buf.n =0; + buf.n=0; + if(!(nb_buf+=nbuf)|| !(buf+=(nbbuf*nbuf))) + return false; + nb_buf.n=nbuf; + sizeBuf = nbbuf; + buf.n =nbbuf*nbuf; + n_buf = nbuf; + memset(nb_buf.ptr,0,sizeof(int)*nbuf); + return true; +} +//********************************************************************************** +bool DataTransfer::setData( Csock_cl* soc, IdataTransfer*datat ) +{ + if(!soc || !datat) + return false; + sc = soc; + dt =datat; + return true; +} + +double DataTransfer::getStatus() +{ + return porcen; +} + +void DataTransfer::cancel() +{ + cancela = true; +} + +//********************************************************************************** +void ThBufDataTransfer::run() +{ + if(data->mode == DataTransfer::MODE_RECEIVE) + runClear(); + else + runFill(); +} +//********************************************************************************** +void ThBufDataTransfer::runFill() +{ + char *pbuf; + data->porcen =0; + ibuf =0; + while(!data->cancela && data->dt_ptotal_p) + { + data->porcen = data->dt_p*100./data->total_p; + if(data->nb_buf[ibuf]<=0) + { + //decide numero de bites a cargar------- + __int64 nbp = (data->nb_total-data->sizeBuf*(data->dt_p)); + if(nbp>data->sizeBuf) + nbp = data->sizeBuf; + //rellena buffer-------------- + pbuf = &data->buf[ibuf*data->sizeBuf]; + __int64 nb = data->dt->getNext_it(pbuf,nbp ); + if(nb!=nbp) + { + data->errorDat =1; + data->mal = true; + data->cancela = true; + continue; + } + //actualiza indices + data->dt_p++; + data->nb_buf[ibuf] = (int)nb; + ibuf = (ibuf+1)%data->n_buf; + continue; + } + Sleep(0); + } + data->porcen = 100; +} +//********************************************************************************** +void ThBufDataTransfer::runClear() +{ + char *pbuf; + ibuf =0; + data->porcen = 0; + //inicia------------------------- + //espera a que se recivan datos + while(!data->cancela && data->total_p<=0) + { + Sleep(1); + } + + if(!data->dt->setPosition_it(data->nb_ini)) + { + data->errorDat =-1; + data->mal = true; + data->cancela = true; + } + + while(!data->cancela && data->dt_ptotal_p) + { + data->porcen = data->dt_p*100./data->total_p; + if(data->nb_buf[ibuf]>0) + { + //decide numero de bites a cargar------- + __int64 nbp = data->nb_buf[ibuf]; + + //rellena buffer-------------- + pbuf = &data->buf[ibuf*data->sizeBuf]; + if(!data->dt->set_it(pbuf,nbp )) + { + data->errorDat =-2; + data->mal = true; + data->cancela = true; + continue; + } + //actualiza indices + data->dt_p++; + data->nb_buf[ibuf] = 0; + ibuf = (ibuf+1)%data->n_buf; + continue; + } + Sleep(0); + } + data->porcen =100; +} + +//********************************************************************************** +void ThSockDataTransfer::run() +{ + if(data->mode == DataTransfer::MODE_RECEIVE) + runReceive(); + else + runSend(); +} +//********************************************************************************** +void ThSockDataTransfer::runSend() +{ + char *pbuf; + //inicia----------------------- + ibuf =0; + //envia cavecera + Head_DataTransfer cab; + cab.version = VERSION_HEAD_DATA_TRANSFER; + cab.nb_total = data->nb_total; + cab.nb_ini = data->nb_ini; + if(!data->sc->envia((BYTE*)&cab,(int) sizeof(cab))) + { + data->errorSoc =1; + data->mal = true; + data->cancela = true; + + + } + + while(!data->cancela && data->sc_ptotal_p) + { + if(data->nb_buf[ibuf]>0) + { + //decide numero de bites a cargar------- + __int64 nbp =data->nb_buf[ibuf]; + if(nbpsizeBuf) + nbp =nbp; + //rellena buffer-------------- + pbuf = &data->buf[ibuf*data->sizeBuf]; + if(!data->sc->envia((BYTE*)pbuf,(int) nbp)) + { + data->errorSoc =2; + data->mal = true; + data->cancela = true; + + continue; + } + + data->sc_p++; + data->nb_buf[ibuf] = 0; + ibuf = (ibuf+1)%data->n_buf; + continue; + } + Sleep(0); + } + + if(!data->cancela && data->sc_p>=data->total_p) + { + if(!data->sc->recibe((BYTE*)&cab,(int) sizeof(cab)) || cab.version != VERSION_HEAD_DATA_TRANSFER || cab.nb_total != data->nb_total) + { + data->errorSoc =3; + data->mal = true; + data->cancela = true; + } + } +} +//********************************************************************************** +void ThSockDataTransfer::runReceive() +{ + char *pbuf; + //inicia----------------------- + ibuf =0; + //envia cavecera + Head_DataTransfer cab; + int nv=0; + bool res =false; + if(!data->sc->Receive((BYTE*)&cab,(int) sizeof(cab)) || cab.version != VERSION_HEAD_DATA_TRANSFER || cab.nb_total <=0) + { + data->errorSoc =-1; + data->mal = true; + + data->cancela = true; + } + else + { + data->nb_ini = cab.nb_ini; + data->nb_total = cab.nb_total; + int pp =(int)(data->nb_total*1./data->sizeBuf); + if(data->nb_total>(pp*data->sizeBuf)) + pp++; + data->total_p = pp; + } + + while(!data->cancela && data->sc_ptotal_p) + { + if(data->nb_buf[ibuf]<=0) + { + //decide numero de bites a cargar------- + __int64 nbp =data->nb_total-((data->sc_p)*data->sizeBuf); + if(nbp>data->sizeBuf) + nbp=data->sizeBuf; + else + nbp =nbp; + //rellena buffer-------------- + pbuf = &data->buf[ibuf*data->sizeBuf]; + if(!data->sc->recibe((BYTE*)pbuf,(int) nbp)) + { + if(data->sc->er->tipo<0) + continue; + data->errorSoc =-2; + data->mal = true; + data->cancela = true; + continue; + } + + data->sc_p++; + data->nb_buf[ibuf] = (int)nbp; + ibuf = (ibuf+1)%data->n_buf; + continue; + } + Sleep(0); + } + + cab.version = VERSION_HEAD_DATA_TRANSFER; + cab.nb_total = data->nb_total; + cab.nb_ini = data->nb_ini; + if(!data->cancela && !data->sc->envia((BYTE*)&cab,(int) sizeof(cab))) + { + data->errorSoc =-3; + data->mal = true; + data->cancela = true; + } +} +//********************************************************************************** \ No newline at end of file diff --git a/DataTransfer.h b/DataTransfer.h new file mode 100644 index 0000000..0a6daf8 --- /dev/null +++ b/DataTransfer.h @@ -0,0 +1,95 @@ +#pragma once +#include "base_head.h" +#include "th.h" +#include "garray.h" +//clase generica de transmision de datos por socket-------------- +/* +la idea de esta clase es que para transmitir datos se usaran 2 socket, uno de envio/recepcion del socket y otro para llenar/vaciar bufferes +*/ + +class DataTransfer; +//thread de socket------- +class UTILES_EXPORT ThSockDataTransfer: public Cth +{ + int ibuf; + void runSend(); + void runReceive(); + + virtual void run(); +public: + DataTransfer *data; + +}; + +//thread de buffer------- +class UTILES_EXPORT ThBufDataTransfer: public Cth +{ + + + int ibuf; + virtual void run(); + void runFill(); + void runClear(); +public: + DataTransfer *data; + +}; +#define VERSION_HEAD_DATA_TRANSFER 100 +typedef struct Head_DataTransfer +{ + int version; //version informacion de usuaros + __int64 nb_total; //numero de bytes totales de los datos + __int64 nb_ini; //numero de usuarios en archivo +}Head_DataTransfer; + +class Csock_cl; +class UTILES_EXPORT DataTransfer +{ + friend class ThBufDataTransfer; + friend class ThSockDataTransfer; + + __int64 nb_total;//numero de bytes totales de los datos + __int64 nb_ini;//byte inicial desde el cual se empieza a transmitir / guardar + Cgarray buf;//buffer + Cgarray nb_buf;//indica el numero de bites cargados en el buffer iesimo + + Csock_cl* sc;//puntero a socket + IdataTransfer*dt; + + int total_p;//total de partes en las que se dividen los datos + int sc_p;//partes recopiladas por th de socket + int dt_p;//partes recopiladas por th de bufer + int n_buf;//numero de bufferes + int sizeBuf;//tamaño de cada buffer + int mode; + + int errorSoc; + int errorDat; + + bool cancela; + bool mal; + double porcen; + ThSockDataTransfer thsoc; + ThBufDataTransfer thbuf; +public: + enum ModeDataTransfer{ + MODE_RECEIVE,//modo recepcion + MODE_SEND//modo transmision + }; + + DataTransfer(void); + ~DataTransfer(void); + + //funciones de configuracion + bool setData(Csock_cl* soc, IdataTransfer*datat); + bool setMode(int mode, int nbbuf = (1024*50),int nbuf=2);//configura el modo y cuantos buffer y de cuantos bytes son cada uno + + bool start(); + + double getStatus(); + bool isCanceled(); + bool currando(); + void cancel(); + void join(); + +}; diff --git a/DijkstraUtiles.cpp b/DijkstraUtiles.cpp new file mode 100644 index 0000000..b2164f1 --- /dev/null +++ b/DijkstraUtiles.cpp @@ -0,0 +1,1303 @@ +#include "StdAfx.h" +#include "DijkstraUtiles.h" +#include "dir_manager.h" +#include "StrArray.h" +#include "..\Olivia\Olivia\olv_tasks_def.h" +/** +* @file olv_geom.h +* Archivo de definiciones de clase de varias utilidades geométricas del programa Olivia. +*/ + +//************************************************************************************* +//Funciones de las estructuras Dijkstra +/** + * Función para la estructura del algoritmo Dijkstra, para iniciar el nodo + */ +void Djkt_nodo::inicia() +{ + dis = (float)MAYUSCULO; + id_padre = -1; + visto = FALSE; + ids_ady.nady=-1; + ids_ady.angs=NULL; + ids_ady.i_conjs=NULL; + ids_ady.ids_padre=NULL; +}; +//************************************************************************************* +BOOL Djkt_nodo::inicia_ex( Djkt_ang_ady *ang ) +{ + inicia(); + + ids_ady=*ang; + ids_ady.angs=NULL; + + if(!ids_ady.inicia_ids()) + return FALSE; + + + return TRUE; +}; +//************************************************************************************* +void Djkt_nodo::libera( ) +{ + ids_ady.libera_ex(); +}; +//************************************************************************************* +/** + * Función para la estructura del algoritmo Dijkstra, para iniciar la cola + */ +void Djkt_cola::inicia(Djkt_nodo *n) +{ + elem = NULL; + nodos = n; + nn=0; +}; +//************************************************************************************* +/** + * Función para la estructura del algoritmo Dijkstra, para poner en la cola + */ +BOOL Djkt_cola::pon(int i) +{ + return pon(i,-1); +}; +//************************************************************************************* +/** + * Función para la estructura del algoritmo Dijkstra, para poner en la cola + */ +BOOL Djkt_cola::pon(int i,int i_inci) +{ + int nv=200; + Djkt_elem_cola *aux = new Djkt_elem_cola(); + Djkt_elem_cola *aux1 = elem; + Djkt_elem_cola *aux2=NULL; + while(!aux && nv>0) + { + + nv--; + Sleep(1); + aux = new Djkt_elem_cola(); + } + if(!aux) + return FALSE; + nn++; + aux->id = i; + aux->id_inci=i_inci; + aux->sig = NULL; + while (true) + { + if (!aux1) + { + elem = aux; + break; + } + if (nodos[aux1->id].dis >= nodos[aux->id].dis) + { + aux->sig = aux1; + if(aux2) + aux2->sig=aux; + if (aux1 == elem) + elem = aux; + break; + } + if (!aux1->sig) + { + aux1->sig = aux; + break; + } + aux2=aux1; + aux1 = aux1->sig; + } + return TRUE; +}; +//************************************************************************************* +/** + * Función para la estructura del algoritmo Dijkstra, para obtener de la cola + */ +int Djkt_cola::dame() +{ + return dame(NULL); +}; +//************************************************************************************* +/** + * Función para la estructura del algoritmo Dijkstra, para obtener de la cola + */ +int Djkt_cola::dame(int *id_inci) +{ + if (!elem) + return -1; + if(nn<=0) + { + elem=NULL; + return -1; + } + nn--; + Djkt_elem_cola *aux = elem; + int res = aux->id; + elem = elem->sig; + if(id_inci) + *id_inci=aux->id_inci; + delete(aux); + return res; +}; +//************************************************************************************* +/** + * Función constructor para la estructura de nodos adyacentes para los ángulos + */ +Djkt_ang_ady::Djkt_ang_ady() +{ + nady=0; + i_conjs=0; + angs=0; + ids_padre=NULL; +} +//************************************************************************************* +/** + * Función destructor para la estructura de nodos adyacentes para los ángulos + */ +void Djkt_ang_ady::libera() +{ + if(i_conjs) + free(i_conjs); + i_conjs=NULL; + if(angs) + { + for(int i=0;i16) + { + nady=nady; + } + //malloc + i_conjs=(int*)malloc(nady*sizeof(int)); + if(!i_conjs) + return FALSE; + for(i=0;iii) && (i_conjs[jj]==-1)) || (i_conjs[jj]==j)) + break; + } + if(ii>=nady || jj>=nady) + return FALSE; + + *ii_=ii; + if(jj_) + *jj_=jj; + + return TRUE; +} +//************************************************************************************* +/** + * Para la estructura de nodos adyacentes para los ángulos, + * pone el ángulo de la conj, entre las adyacentes i y j + */ +BOOL Djkt_ang_ady::pon_ang_i_j(int i,int j, BYTE ang) +{ + int ii,jj; + + if(!dame_ii_jj(i,j,&ii,&jj)) + return FALSE; + + i_conjs[ii]=i; + i_conjs[jj]=j; + angs[ii][jj]=ang; + + return TRUE; +}; +//************************************************************************************* +/** + * Para la estructura de nodos adyacentes para los ángulos, + * devuelve el ángulo de la conj, entre las adyacentes i y j + */ +BOOL Djkt_ang_ady::dame_ang_i_j(int i,int j, BYTE *ang, BOOL inds_abs) +{ + int ii,jj; + + if(inds_abs) + { + if(!dame_ii_jj(i,j,&ii,&jj)) + return FALSE; + } + else + { + ii=i; + jj=j; + } + + *ang=angs[ii][jj]; + return TRUE; +} +//************************************************************************************* +/** + * Para la estructura de nodos adyacentes para los ángulos, + * pone que para llegar al nodo actual desde i_orig, el padre es j_padre + */ +BOOL Djkt_ang_ady::pon_padre(int i_orig,int j_padre, double dis, BOOL inds_abs) +{ + int ii,jj; + + if(inds_abs) + { + if(!dame_ii_jj(i_orig,j_padre,&ii,&jj)) + return FALSE; + } + else + { + ii=i_orig; + jj=j_padre; + } + + ids_padre[ii].id=jj; + ids_padre[ii].dis=(float)dis; + + return TRUE; +}; +//************************************************************************************* +/** + * Para la estructura de nodos adyacentes para los ángulos, + * devuelve que el padre es j_padre para ir al nodo actual desde i_orig + */ +BOOL Djkt_ang_ady::dame_padre(int i_orig,int *j_padre, double *dis, BOOL inds_abs) +{ + int ii,jj; + + if(inds_abs) + { + if(!dame_ii_jj(i_orig,-1,&ii,&jj)) + return FALSE; + } + else + { + ii=i_orig; + jj=-1; + } + + *j_padre = i_conjs[ids_padre[ii].id]; + *dis = ids_padre[ii].dis; + + return TRUE; +}; +//************************************************************************************* +/* + * Guarda a disco + */ +BOOL Djkt_ang_ady::guarda(HeadCostAng hd, int ic, char *path , char *ext) +{ + HANDLE hfile = INVALID_HANDLE_VALUE; + int nb, i; + char file[MAX_PATH]; + + sprintf_s(file,MAX_PATH,"%s%06d.%s",path,ic,ext); + + //crea archivo----------------------------------- + hfile = CreateFile(file, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + if (hfile == INVALID_HANDLE_VALUE) + { + i=GetLastError(); + return FALSE; + } + + //graba cabecera------------ + nb = sizeof(hd); + //calcula el nb + hd.n=nady; //* BYTE + if (nb != _lwrite((int)hfile, (LPCCH)&hd, nb)) + { + goto va_mal; + } + + //guarda la matriz de conjs ady + nb=sizeof(int)*nady; + if (nb != _lwrite((int)hfile, (LPCCH) i_conjs, nb)) + { + goto va_mal; + } + //guarda la matriz de ángulos + nb=nady; + for(i=0;idimensiona(((__int64)n)*n)) + goto va_mal; + visto_ang->setAll(FALSE); + + if(angs) + { + ang_ok=TRUE; + for (i=0; iset(((__int64)id_inci)*n+sig,TRUE); + //se revisa cada nodo + for (i = 0; i < n; i++) + { + if (costes[i][sig] >= MAYUSCULO) + continue; + if ((*visto_ang)[((__int64)sig)*n+i])//si visto se pasa de el + continue; + if(angs) + { + if(!angs[sig].dame_ii_jj(i,-1,&ii,NULL)) + continue; + + if(distancias[sig].ids_ady.ids_padre[ii].id!=-1) + { + if(!angs[sig].dame_ii_jj(distancias[sig].ids_ady.ids_padre[ii].id,-1,&jj,NULL)) + continue; + + if(!angs[sig].angs[ii][jj]) + continue; + + } + d=distancias[sig].ids_ady.ids_padre[ii].dis + costes[i][sig]; + + if (distancias[i].dis > d)//se actualiza distancia si procede + { + if(d<0) + d=d; + distancias[i].dis = (float)d; + distancias[i].id_padre = sig; + visto_ang->set(((__int64)sig)*n+i,0); + if (!q.pon(i,sig)) + goto va_mal; + } + + if(!angs[i].dame_ii_jj(sig,-1,&sigr,NULL)) + continue; + + for(jj=0;jj1)) + continue; + if(!angs[i].angs[jj][sigr]) + continue; + + if (distancias[i].ids_ady.ids_padre[jj].dis > d)//se actualiza distancia si procede + { + distancias[i].ids_ady.ids_padre[jj].dis = (float)d; + distancias[i].ids_ady.ids_padre[jj].id = sig; + visto_ang->set(((__int64)sig)*n+i,0); + if (!q.pon(i,sig)) + goto va_mal; + } + } + } + else + { + //encontrado adyacente se hace la relajacion---------------- + d = distancias[sig].dis + costes[i][sig]; + if (distancias[i].dis > d)//se actualiza distancia si procede + { + distancias[i].dis = (float)d; + distancias[i].id_padre = sig; + if (!q.pon(i,sig)) + goto va_mal; + } + } + + + } + } + res = TRUE; + + if (nodos) + { + *nodos = distancias; + distancias = NULL; + } + +va_mal: + if (distancias) + free(distancias); + while (q.dame() >= 0); + + return res; +} +//************************************************************************************* +/* + * Da la ruta hasta el nodo final con el que se hizo dijkstra desde 'id_ini' + * Hay que haber llamado antes a dijkstra, y el array 'nodos' de salida es el que aquí + * es entrada, de tamaño 1xn. + * En 'secu' devuelve un array de la secuencia a seguir desde el nodo 'id_ini' hasta el nodo final + * Es de tamaño el número de nodos de la red, pero sólo están ocupados los 'n' primeros con la secuencia. + */ +double DijkstraUtiles::ruta_dj_inv(int id_ini, int *secu, Djkt_nodo *nodos, int nmax, int *n) +{ + int padre= id_ini; + int nn = 0; + while (padre>=0 && nn=0 && nn0; + } + HANDLE hfile = INVALID_HANDLE_VALUE; + int nb; + char p[MAX_PATH]; + sprintf_s(p,MAX_PATH, "%s_%ld.%s",path, 0,extension); + hfile = CreateFile(p, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + if (hfile == INVALID_HANDLE_VALUE) + return FALSE; + nb = sizeof(hd); + if (nb != _lread((int)hfile,&hd, nb)) + { + goto va_mal; + } + if(hfile != INVALID_HANDLE_VALUE) + CloseHandle(hfile); + sizn=sizeof(Djkt_nodo)+hd.max_conex*(sizeof(Djkt_ids_pdr)+sizeof(int)+sizeof(BYTE)*hd.max_conex); + return (hd.version== VERSION_DJ_ARCHI && hd.max_conex>0 && hd.nn>0 && sizn>0); + +va_mal: + if(hfile != INVALID_HANDLE_VALUE) + CloseHandle(hfile); + return FALSE; + + +} +//************************************************************************************* +BOOL Cdijkstra_arch::add_b( Djkt_nodo* blq, int iref, int inod, BOOL pon_inf ) +{ + HANDLE hfile = INVALID_HANDLE_VALUE; + int nb, i, nbt, j; + char p[MAX_PATH]; + sprintf_s(p,MAX_PATH,"%s_%ld.%s",path,iref,extension); + Head_dj_arch hdl; + //abre archivo----------------------------------- + hfile = CreateFile(p, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + if (hfile == INVALID_HANDLE_VALUE) + { + hfile = CreateFile(p, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + + + if (hfile == INVALID_HANDLE_VALUE) + { + //wgeotext(LOG_TODO,"Cdijkstra_arch::add_b","Error no se puede abrir archivo: %s", p); + + i=GetLastError(); + return FALSE; + } + //graba cabecera------------ + hdl=hd; + hdl.nb=0; + nb = sizeof(hdl); + if (nb != _lwrite((int)hfile, (LPCCH)&hdl, nb)) + { + //wgeotext(LOG_TODO,"Cdijkstra_arch::add_b","Error no se puede grabar cabecera de archivo: %s", p); + goto va_mal; + } + } + else + { + //lee cabecera------------- + nb = sizeof(hdl); + if (nb != _lread((int)hfile, &hdl, nb)) + { + //wgeotext(LOG_TODO,"Cdijkstra_arch::add_b","Error no se puede leer cabecera de archivo: %s", p); + + goto va_mal; + } + } + //va a lo ultimo--------------------------------- + if ( SetFilePointer(hfile, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) + { + //wgeotext(LOG_TODO,"Cdijkstra_arch::add_b","Error no se puede ir al final del archivo: %s", p); + + goto va_mal; + } + //guarda bloque--------------------------------- + for (i=0; i0) + { + if ( SetFilePointer(hfile, nb, NULL, FILE_CURRENT) == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) + { + //wgeotext(LOG_TODO,"Cdijkstra_arch::get_b","Error al ir al siguiente nodo, en nodo %ld archivo: %s", i, p); + + goto va_mal; + } + } + } + if(hfile != INVALID_HANDLE_VALUE) + CloseHandle(hfile); + return buf_res; +va_mal: + if(hfile != INVALID_HANDLE_VALUE) + CloseHandle(hfile); + if(buf_res && !buf) + { + for (i=0; i=0) + { + nnod++; + id_plan=namb++; + + } + if(idinstal>=0) + { + nnod++; + id_instal=namb; + } + + //pide memoria + buf=(float*)realloc(dis,nnod*nnod*sizeof(float) ); + if(!buf) + { + ia=NULL; + return FALSE;//sin memoria + } + dis=buf; + for(i=nnod*nnod-1; i>=0; i--) + { + dis[i]=(float)MAYUSCULO; + } + return TRUE; + +} +//************************************************************************************* +void Cdijkstra_arch::pon_info_amb( Djkt_nodo* nodos, int iref,int ib ) +{ + int i, j, k; + if(!ia) + return; + //calcula fila--- + j=(iref*nod_amb+ib)*nnod; +#ifdef DEBUG + if (!AfxCheckMemory()) + C_log::log("Cdijkstra_arch","Error memoria"); + +#endif + for (i=0; iget(i,k)].dis; + if(nodos[ia->get(i,k)].dis<0) + nodos[ia->get(i,k)].dis=nodos[ia->get(i,k)].dis; + } + } +#ifdef DEBUG + if (!AfxCheckMemory()) + C_log::log("Cdijkstra_arch","Error memoria"); + +#endif + if(nod_instal>=0) + { + dis[j+nambi*nod_amb+id_instal-nambi]=nodos[nod_instal].dis; + if(nodos[nod_instal].dis<0) + nodos[nod_instal].dis=nodos[nod_instal].dis; + } +#ifdef DEBUG + if (!AfxCheckMemory()) + C_log::log("Cdijkstra_arch","Error memoria"); + +#endif + if(nod_plan>=0) + { + dis[j+nambi*nod_amb+id_plan-nambi]=nodos[nod_plan].dis; + if(nodos[nod_plan].dis<0) + nodos[nod_plan].dis=nodos[nod_plan].dis; + } +#ifdef DEBUG + if (!AfxCheckMemory()) + C_log::log("Cdijkstra_arch","Error memoria"); + +#endif +} +//************************************************************************************* +float Cdijkstra_arch::dame_dis( int aorig,int norig, int ades, int n_des ) +{ + int i=aorig-nambi; + if(nod_amb<=norig) + norig=0; + if(nod_amb<=n_des) + n_des=0; + if(i<0) + i=0; + aorig-=i; + return dis[(ades*nod_amb+n_des)*nnod + aorig*nod_amb+norig+i]; +} +//************************************************************************************* +BOOL Cdijkstra_arch::graba_dis(int id) +{ + Cgarray buf; + char p[MAX_PATH]; + sprintf(p,"%s_%ld.%s", path, id,TASKS_EXT_DIS); + Cb_file f; + if(!f.abre(p,2,TRUE)) + return FALSE; + buf.ptr=dis; + buf.n =nnod*nnod; + BOOL res =buf.graba(&f); + buf.ptr=NULL; + buf.n =0; + return res; + +} +//************************************************************************************* +BOOL Cdijkstra_arch::lee_dis() +{ + Cb_file f; + StrArray files; + char sext[MAX_PATH]; + strcpy(sext, path); + Cgarray buf; + //pilla archivos----------------------- + if(!Cdir_manager::listar(Cdir_manager::dir_anterior(sext), &files)) + return FALSE; + char *file; + for (int i = 0; i +#include +#include +#include "mapmatrix.h" +#ifndef MAYUSCULO +#define MAYUSCULO (double) 1.e+30 + +#endif +#ifndef MINUSCULO +#define MINUSCULO (double) 1.e-20 +#endif + +#define EXT_ARCH_DIJ_DEFAULT "ndj" +#define NOMB_ARCH_DIJ_DEF "snodos_dj" + +/** + * Estructura de elemento de la cola para el cálculo de caminos óptimos por Dijkstra + */ +struct Djkt_elem_cola +{ + int id; // dat; + inline BOOL operator[](__int64 i) + { + BYTE j =(BYTE)(1<<(i%(sizeof(BYTE)*8))); + return (BOOL)((dat[(int)(i/(sizeof(BYTE)*8.))] & j) == j); + } + inline void set(__int64 i, BOOL v) + { + BYTE j; + j =(BYTE)(1<<(i%(sizeof(BYTE)*8))); + + if(!v) + { + j = ~j; + dat[(int)(i/(sizeof(BYTE)*8.))] &= j; + return; + } + dat[(int)(i/(sizeof(BYTE)*8.))] |= j; + } + + inline BOOL dimensiona(__int64 n) + { + dat.n = 0; + int nn = (int)(0.5+n/(sizeof(BYTE)*8.)); + if(!(dat+=nn)) + return FALSE; + dat.n = nn; + return TRUE; + } + inline void setAll(BOOL v) + { + BYTE j = 0; + if(v) + j =~j; + memset(dat.ptr, j, dat.n*sizeof(BYTE)); + } +}; +//************************************************************************************* +class UTILES_EXPORT DijkstraUtiles +{ +public: + static BOOL dijkstra_ang_inv_ok(CmapMatFloat &costes, Djkt_ang_ady *angs, int n, int fin, Djkt_nodo **nodos, FlagsArray *visto_ang_); + static double ruta_dj_inv_ok(int id_ini, int *secu, Djkt_nodo *nodos, int nmax, int *n); + static double ruta_dj_inv(int id_ini, int *secu, Djkt_nodo *nodos, int nmax, int *n); +}; + +//************************************************************************************* +/** +* Clase de manejo de archivos de nodos djtra +* cada archivo tiene un numero de bloques o array de nodos de longitud fija "nnod" +*/ +//estructura cabecera de archivo +typedef struct Head_dj_arch +{ + int version; //version del archivo + int nn; //numero de nodos por bloque + int nb; //numero de bloques del dj + int max_conex; //maximo de conexiones por nodo + +}Head_dj_arch; +#define VERSION_DJ_ARCHI 100 +#define MAX_CONEX_DJ_ARCHI 16 + +class UTILES_EXPORT InfoIndice +{ +public: + virtual int get(int iamb, int iextremo) = 0;//da del ambito iamb el indice a inicio o a fin //si iextremo es o o 1 +}; + +class UTILES_EXPORT Cdijkstra_arch +{ +public: + char extension[16];//extension de archivos + char path[MAX_PATH];//nombre sin extension + Head_dj_arch hd;//cabecera de archivo + int sizn;//tamaño en BYTES de cada nodo + BOOL salta_ids_padres; + //int flags;//0x1-->modo escritura 0x2-->modo lectura + //info de distancias ambitos + float *dis;//distancia de un nodo a otro (matriz de nnod*nnod) + int nod_amb;//nodos por ambito + int nambi;//numero de ambitos + int nnod;//numero de nodos por fila + int id_instal;//fila planta + int id_plan;//fila instal + int nod_instal;//nodo instalacion + int nod_plan;//nodo planta + int tip_ambitos; + + InfoIndice* ia;//puntero a info asoc + + //funciones-------------------------------------------------------------------------- + Cdijkstra_arch(); + ~Cdijkstra_arch(); + + BOOL inicia(char* path_arch, BOOL nuevo=FALSE, BOOL borra = TRUE, int n_nod=0, int max_conex=MAX_CONEX_DJ_ARCHI);//si nuevo -> crea vacio + BOOL add_b(Djkt_nodo* blq, int iref, int inod, BOOL pon_inf=FALSE);//añade un bloque a el archivo + BOOL inicia_inf_amb(InfoIndice* ina, int namb,int tip_amb, int id_instal=-1, int id_plan=-1); + void pon_info_amb(Djkt_nodo* nodos, int iref,int ib); + Djkt_nodo* get_b(int iref, int ibloq, Djkt_nodo* buf=NULL);//develve el bloque ibloq-esimo + float dame_dis(int aorig,int norig, int ades, int n_des); + + Djkt_nodo* dame_buf_nodos(BOOL angulos=FALSE ); + void libera_buf(Djkt_nodo* buf ); + BOOL graba_dis(int id); + BOOL lee_dis(); +}; +#endif \ No newline at end of file diff --git a/FdataTable.cpp b/FdataTable.cpp new file mode 100644 index 0000000..d8a6203 --- /dev/null +++ b/FdataTable.cpp @@ -0,0 +1,10 @@ +#include "StdAfx.h" +#include "FdataTable.h" + +FdataTable::FdataTable(void) +{ +} + +FdataTable::~FdataTable(void) +{ +} diff --git a/FdataTable.h b/FdataTable.h new file mode 100644 index 0000000..e73175d --- /dev/null +++ b/FdataTable.h @@ -0,0 +1,21 @@ +#pragma once +#include "base_head.h" + +//clase para gestiona una tabla de datos generica +class UTILES_EXPORT FdataTable +{ + +public: + enum DataType + { + NdefData=0, + BoolData, + IntData, + DoubleData, + StringData, + BinaryData + }; + + FdataTable(void); + ~FdataTable(void); +}; diff --git a/Fdbf.cpp b/Fdbf.cpp new file mode 100644 index 0000000..600e680 --- /dev/null +++ b/Fdbf.cpp @@ -0,0 +1,538 @@ +#include "StdAfx.h" +#include "Fdbf.h" +//***************************************************************************************** +Fdbf::Fdbf(void) +{ +} +//***************************************************************************************** +Fdbf::~Fdbf(void) +{ +} +//***************************************************************************************** +bool Fdbf::lee( Cb_file *file) +{ + int ncol; + colm.n =0; + iniCol.n =0; + buf.n=0; + if(!file->lee(&head, sizeof(head))) + return false; + ncol = (head.nb_cab - sizeof(Hdr_dbf) - 1) / sizeof(Fld_dbf); + if(ncol<=0) + return false; + if(!(colm+=ncol)) + return false; + if(!(iniCol+=ncol)) + return false; + colm.n = ncol; + iniCol.n = ncol; + //pilla info de campos----------------------- + if(!file->lee(&colm[0], sizeof(Fld_dbf)*colm.n)) + return false; + int aux =1; + for(int i =0; ilee(&ncol, 1)) + return false; + if(!(buf+=head.nb_rec)) + return false; + buf.n = head.nb_rec; + f= file; + nReadRow =0; + return true; +} +//***************************************************************************************** +int Fdbf::leeNexRow()//devuelve 1 si ok 0 si no mas -1 si error +{ + if(nReadRow>=head.nrec) + return 0; + if(!f->lee(&buf[0], head.nb_rec)) + return -1; + nReadRow++; + return 1; +} +//***************************************************************************************** +char* Fdbf::getName(int ncol) +{ + if(ncol>=colm.n) + return 0; + return colm[ncol].nombre; +} +//***************************************************************************************** +BYTE Fdbf::getType(int ncol) +{ + if(ncol>=colm.n) + return 0; + return colm[ncol].tipo; +} +//***************************************************************************************** +int Fdbf::getSize(int ncol) +{ + if(ncol>=colm.n) + return 0; + return (int)colm[ncol].nb; +} +//***************************************************************************************** +int Fdbf::getNrow() +{ + return head.nrec; +} +//***************************************************************************************** +int Fdbf::getNcolm() +{ + return colm.n; +} +//***************************************************************************************** +char* Fdbf::get(int ncol) +{ + if(ncol>=colm.n) + return 0; + //if(!f->lee(&buf[0], head.nb_rec)) + // return NULL; + return &buf[iniCol[ncol]]; +} +//***************************************************************************************** +bool Fdbf::bufMem(int ncol) +{ + char*d = get(ncol); + int nb = colm[ncol].nb+1; + if(buf2.mescribe(&head, sizeof(head))) + return false; + return true; +} +//***************************************************************************************** +bool Fdbf::setCol(int icol, char *name, BYTE type, int size, int ndecimals) +{ + if(icol<0 || icol>colm.n) + return false; + nReadRow =-1; + int i =0; + //copia de nombre segura-------- + for(; i<11; i++) + { + colm[icol].nombre[i]=name[i]; + if(!name[i]) + break; + } + colm[icol].nombre[i] =0; + //------------------------------ + colm[icol].tipo = type; + colm[icol].nb = size; + colm[icol].nd = ndecimals; + + switch(type) + { + case(DBF_TYPE_DATA_I64): + case(DBF_TYPE_DATA_STR): + case(DBF_TYPE_DATA_BIN): + case(DBF_TYPE_DATA_I): + colm[icol].nd =0; + break; + } + + return true; +} +//***************************************************************************************** +bool Fdbf::iniciaRecords() +{ + if(nReadRow>=0) + return true; + nReadRow =0; + int nb =1; + for(int i =0; iirAini()) + return false; + if(!f->escribe(&head, sizeof(head))) + return false; + //graba info------------------------ + if(!f->escribe(&colm[0], sizeof(Fld_dbf)*colm.n)) + return false; + //graba terminacion de head + char ff = 13; + if(! f->escribe(&ff, sizeof(ff))) + return false; + return true; +} +//***************************************************************************************** +bool Fdbf::addVal(int icol, int v) +{ + char st1[64]; + if(!iniciaRecords()) + return false; + buf2.n =0; + + if(!(buf2+=(colm[icol].nb+1))) + return false; + buf2.n =colm[icol].nb+1; + + sprintf(st1,"%%0%ldd",colm[icol].nb); + sprintf(&buf2[0],st1,v); + + int n = (int)strlen(&buf2[0]); + if (n > colm[icol].nb) + n = colm[icol].nb; + //alinea a la derecha + char *st = &buf[iniCol[icol]]; + memset(st,0x20, colm[icol].nb); + memcpy(st+colm[icol].nb-n,&buf2[0],n); + return true; +} +//***************************************************************************************** +bool Fdbf::addVal(int icol, double v) +{ + char st1[64]; + if(!iniciaRecords()) + return false; + buf2.n =0; + + if(!(buf2+=colm[icol].nb)) + return false; + buf2.n =colm[icol].nb; + + sprintf(st1,"%%1.%ldlf",colm[icol].nd); + sprintf(&buf2[0],st1,v); + + int n =(int) strlen(&buf2[0]); + if (n > colm[icol].nb) + n = colm[icol].nb; + //alinea a la derecha + char *st = &buf[iniCol[icol]]; + memset(st,0x20, colm[icol].nb); + memcpy(st+colm[icol].nb-n,&buf2[0],n); + return true; +} +//***************************************************************************************** +bool Fdbf::addVal(int icol, __int64 v) +{ + char st1[32]; + CTime tt(v); + + if(!iniciaRecords()) + return false; + + buf2.n =0; + + if(!(buf2+=colm[icol].nb)) + return false; + buf2.n =colm[icol].nb; + + strcpy(st1,tt.Format("%Y%m%d")); + + sprintf(&buf2[0],st1,v); + + int n =(int) strlen(&buf2[0]); + if (n > colm[icol].nb) + n = colm[icol].nb; + //alinea a la derecha + char *st = &buf[iniCol[icol]]; + memset(st,0x20, colm[icol].nb); + memcpy(st+colm[icol].nb-n,&buf2[0],n); + + return true; +} +//***************************************************************************************** +bool Fdbf::finRow() +{ + //comprueba maximo + if(nReadRow>= head.nrec) + return false; + nReadRow++; + buf[0]=' '; + //graba buffer en archivo + if(!f->escribe(&buf[0], buf.n)) + return false; + //si es el final graba head + if(nReadRow>= head.nrec) + { + buf[0]=26; + if(!f->escribe(&buf[0], 1)) + return false; + } + return true; +} +//***************************************************************************************** +bool Fdbf::addVal(int icol, char* v) +{ + if(!iniciaRecords()) + return false; + int i =0; + char *dt=&buf[iniCol[icol]]; + double maxi = colm[icol].nb; + //copia de nombre segura-------- + for(; iDbfSet(nrow, ncolm)) + return false; + //prepara las columnas--------------- + for(int i =0; iDbfSetColm(dbf.getName(i),dbf.getType(i),dbf.getSize(i))) + return false; + } + //recorre las filas--------------- + int error =dbf.leeNexRow(); + while(error ==1) + { + //por cada fila recorre las columnas + for(int i =0; iDbfaddVal(i,dbf.getStr(i)); + break; + case(DBF_TYPE_DATA_I64): + res =lr->DbfaddVal(i,dbf.getI64(i)); + break; + case(DBF_TYPE_DATA_D): + res =lr->DbfaddVal(i,dbf.getD(i)); + break; + case(DBF_TYPE_DATA_BOOL): + return false; + break; + case(DBF_TYPE_DATA_BIN): + res =lr->DbfaddVal(i,dbf.get(i)); + break; + case(DBF_TYPE_DATA_I): + res =lr->DbfaddVal(i,dbf.getI(i)); + break; + default: + return false; + } + if(!res) + return false; + } + if(!lr->DbfFinRow()) + return false; + error =dbf.leeNexRow(); + } + + return error == 0 && lr->DbfFinRow(); + +} +//***************************************************************************************** +bool ManagerDbf::grabar(char* file, ListenerDbf_R* lw) +{ + Cb_file f; + if(!f.abre(file,2,true)) + return false; + return grabar(&f,lw); +} +//***************************************************************************************** +bool ManagerDbf::grabar(Cb_file* f, ListenerDbf_R* lw) +{ + Fdbf dbf; + int nrow =-1; + int ncolm =-1; + char name[11]; + BYTE type; + int size; + int nd; + if(!lw->DbfGet(&nrow, &ncolm) /*|| nrow<=0 || ncolm<=0*/) + return false; + if(!dbf.set(ncolm, nrow, f)) + return false; + //prepara las columnas--------------- + for(int i =0; iDbfGetColm(i,name,&type,&size,&nd)) + return false; + if(!dbf.setCol(i,name,type,size,nd)) + return false; + } + //recorre las filas--------------- + char *cv; + void *vv; + double dv; + int iv; + __int64 i64v; + for(int j =0;jDbfGetVal(j, i, &cv) && dbf.addVal(i,cv); + break; + case(DBF_TYPE_DATA_I64): + res =lw->DbfGetVal(j, i, &i64v) && dbf.addVal(i,i64v); + break; + case(DBF_TYPE_DATA_D): + res =lw->DbfGetVal(j, i, &dv) && dbf.addVal(i,dv); + break; + case(DBF_TYPE_DATA_BOOL): + return false; + break; + case(DBF_TYPE_DATA_BIN): + res =lw->DbfGetVal(j, i, &vv) && dbf.addVal(i,vv); + break; + case(DBF_TYPE_DATA_I): + res = lw->DbfGetVal(j, i, &iv) && dbf.addVal(i,iv); + + break; + default: + return false; + } + if(!res) + return false; + } + if(!lw->DbfFinW()) + return false; + if(!dbf.finRow()) + return false; + } + + return true; +} +//***************************************************************************************** \ No newline at end of file diff --git a/Fdbf.h b/Fdbf.h new file mode 100644 index 0000000..94a7eef --- /dev/null +++ b/Fdbf.h @@ -0,0 +1,184 @@ +#pragma once +#ifndef Fdbf_H +#define Fdbf_H +#include "base_head.h" +#include "b_file.h" +#include "garray.h" +#pragma pack(1) + +typedef struct Hdr_dbf +{ + BYTE ver,year,mes,dia; // cuatro primeros bytes + long nrec; // nº de records (filas) + short nb_cab; // nº de bytes de la cabecera + short nb_rec; // nº de bytes de cada record + BYTE res[20]; +} Hdr_dbf; + +typedef struct Fld_dbf +{ + char nombre[11]; // nombre del campo + BYTE tipo; // tipo de campo + // C caracter + // N número + // L lógico (Y/N,T/F, y mas) + // D fecha (YYYYMMDD) + // F float, double + BYTE res1[4]; + BYTE nb; // nº de bytes del campo + //Nuevo elena 201709 + union + { + BYTE res2[15]; + struct{ + + + BYTE nd; //nº de decimales + BYTE res2_[14]; + }; + }; +} Fld_dbf; + +#pragma pack(8) + +#define DBF_TYPE_DATA_STR 'C' +#define DBF_TYPE_DATA_I64 'D' +#define DBF_TYPE_DATA_D 'F' +#define DBF_TYPE_DATA_BOOL 'L' +#define DBF_TYPE_DATA_BIN 'M' +#define DBF_TYPE_DATA_I 'N' + +//clase base de dbf------------------------------------- +class UTILES_EXPORT Fdbf +{ + Hdr_dbf head; + Cgarraycolm; + Cgarray buf;//buffer de fila + Cgarray buf2;//buffer auxi + + CgarrayiniCol;//indice a el bite deonde empieza la columna iesima dentro de una fila + Cb_file *f; + int nReadRow;//numero de filas leidas actualmente +public: + Fdbf(void); + ~Fdbf(void); + + //funciones de lectura + bool lee( Cb_file *file); + int leeNexRow();//devuelve 1 si ok 0 si no mas -1 si error + + double getD(int ncol); + int getI(int ncol); + char* getStr(int ncol); + __int64 getI64(int ncol); + char* get(int ncol);//devuelve buffer tal cual + + BYTE getType(int ncol); + char* getName(int ncol); + int findCol(char *name); + + int getSize(int ncol); + int getNrow(); + int getNcolm(); + //funciones de escritura + bool set(int ncol, int nRow, Cb_file *file); + bool setCol(int icol, char *name, BYTE type, int size, int ndecimals=0); + + bool addVal(int icol, int v); + bool addVal(int icol, double v); + bool addVal(int icol, __int64 v); + bool addVal(int icol, char* v); + bool addVal(int icol, void* v); + bool finRow(); + +private: + bool bufMem(int ncol); + bool iniciaRecords(); +}; + +//clase lisener de lectura +class UTILES_EXPORT ListenerDbf_W +{ +public: + virtual bool DbfSet(int nrow, int ncolm){return true;} + virtual bool DbfSetColm(char* name, BYTE type, int size){return true;} + virtual bool DbfaddVal(int icol, int v){return true;} + virtual bool DbfaddVal(int icol, double v){return true;} + virtual bool DbfaddVal(int icol, __int64 v){return true;} + virtual bool DbfaddVal(int icol, char* v){return true;} + virtual bool DbfaddVal(int icol, void* v){return true;} + virtual bool DbfFinRow(){return true;} + virtual bool DbfFinR(){return true;} + +}; +//clase lisener de escritura +class UTILES_EXPORT ListenerDbf_R +{ +public: + virtual bool DbfGet(int *nrow, int *ncolm){return false;} + virtual bool DbfGetColm(int icol, char* name, BYTE *type, int *size, int*ndecimal){return false;} + virtual bool DbfGetVal(int irow, int icol, int* v){return false;} + virtual bool DbfGetVal(int irow, int icol, double* v){return false;} + virtual bool DbfGetVal(int irow, int icol, __int64* v){return false;} + virtual bool DbfGetVal(int irow, int icol, char** v){return false;} + virtual bool DbfGetVal(int irow, int icol, void** v){return false;} + virtual bool DbfFinW(){return false;} + +}; + + +//clase manager dbf------------------------- +class UTILES_EXPORT ManagerDbf +{ +public: + static bool leer(Cb_file *file, ListenerDbf_W* lr); + static bool grabar(Cb_file *file, ListenerDbf_R* lw); + + static bool leer(char* file, ListenerDbf_W* lr); + static bool grabar(char* file, ListenerDbf_R* lw); +}; + +#endif +/* +ejemplo de uso-------------------------------- +escritura--------- +if(!f.abre("d:\\temp\\p2.dbf",2,true)) +error =true; +if(!dbf.set(3,5,&f)) +error = true; +if(!dbf.setCol(0,"id",DBF_TYPE_DATA_I,10)) +error = true; +if(!dbf.setCol(1,"idf",DBF_TYPE_DATA_D,10,3)) +error = true; +if(!dbf.setCol(2,"str",DBF_TYPE_DATA_STR,128)) +error = true; +for(int i =0; i<5; i++) +{ +if(!dbf.addVal(0,i)) +error = true; +if(!dbf.addVal(1,i+(i*1./10))) +error = true; +if(!dbf.addVal(2,"holaHolita")) +error = true; +if(!dbf.finRow()) +error = true; +} +f.cierra(); +//lectura +if(!f.abre("d:\\temp\\p2.dbf",1)) +error =true; +if(!dbf.lee(&f)) +error = true; +idd =dbf.leeNexRow(); +while(idd ==1) +{ +int ii = dbf.getI(0); +double d= dbf.getD(1); +char* ss = dbf.getStr(2); + +ii++; +d++; +ss[0]=0; +idd =dbf.leeNexRow(); +} +*/ \ No newline at end of file diff --git a/Fshape.cpp b/Fshape.cpp new file mode 100644 index 0000000..ea2baea --- /dev/null +++ b/Fshape.cpp @@ -0,0 +1,648 @@ +#include "StdAfx.h" +#include "Fshape.h" +#include +//************************************************************************** +int Fshape::inv_4(int *pb) +{ + char (*pc)[],(*pd)[]; + int j,dw; + + dw = *pb; + pc = (char (*)[]) &dw; + pd = (char (*)[]) pb; + for (j=0; j<4; j++) + (*pd)[j] = (*pc)[3-j]; + + return(dw); +} +//************************************************************************** +Fshape::Fshape(void) +{ +} +//************************************************************************** +Fshape::~Fshape(void) +{ +} +//************************************************************************** +bool Fshape::leeHead(Cb_file *file) +{ + f = file; + if(!f->lee(&head, sizeof(head))) + return false; + inv_4(&head.code); + inv_4(&head.nb); + + head.nb = 2 * head.nb- sizeof(head); + switch(head.tipo) + { + case(Point): + nc = 2; + ReadType = Rpoint; + break; + case(PolyLine): + nc = 2; + ReadType = RPolyLine; + break; + case(Polygon): + nc = 2; + ReadType = Rpolygon; + break; + case(MultiPoint): + nc = 2; + ReadType = RMpoint; + break; + + case(PointZ): + nc = 4; + ReadType = Rpoint; + break; + case(PolyLineZ): + nc = 4; + ReadType = RPolyLine; + break; + case(PolygonZ): + nc = 4; + ReadType = Rpolygon; + break; + case(MultiPointZ): + nc = 4; + ReadType = RMpoint; + break; + + case(PointM): + nc = 3; + ReadType = Rpoint; + break; + case(PolyLineM): + nc = 3; + ReadType = RPolyLine; + break; + case(PolygonM): + nc = 3; + ReadType = Rpolygon; + break; + case(MultiPointM): + nc = 3; + ReadType = RMpoint; + break; + default: + return false; + } + return true; +} +//************************************************************************** +bool Fshape::LeeRecord() +{ + //lee cab + int nb; + if(head.nb<=0) + return false; + if(!f->lee(&headr, sizeof(headr))) + return false; + head.nb-=sizeof(headr); + inv_4(&headr.nrec); + inv_4(&headr.nb); + //tipo incluido en cabecera + headr.nb = 2 * headr.nb-sizeof(int); + //lee contenido record; + bufRecord.n = 0; + if(!(bufRecord+= headr.nb)) + return false; + bufRecord.n = headr.nb; + if(!f->lee(&bufRecord[0], bufRecord.n)) + return false; + head.nb-=bufRecord.n; + numPart = 0; + nb = 0; + maxC = NULL; + mimC = NULL; + mimaM = NULL; + mimaZ = NULL; + ptosM = NULL; + ptos = NULL; + ptosZ = NULL; + + switch (ReadType) + { + case Rpoint: + numPart = 0; + ptos = (double*)&bufRecord[nb];//salta el tipo + tc = (bufRecord.n-nb)/sizeof(double); + npt =tc/nc; + break; + case RMpoint: + mimC = (double*)&bufRecord[nb]; + nb +=2*sizeof(double); + maxC = (double*)&bufRecord[nb]; + nb +=2*sizeof(double); + npt = *(int*)&bufRecord[nb]; + nb += sizeof(int); + ptos = (double*)&bufRecord[nb];//salta el tipo + nb+=sizeof(double)*2*npt; + if(nc>2) + { + if(nc<4) + { + mimaM = (double*)&bufRecord[nb]; + nb+=2*sizeof(double); + ptosM = (double*)&bufRecord[nb]; + nb+=npt*sizeof(double); + } + else + { + mimaZ = (double*)&bufRecord[nb]; + nb+=2*sizeof(double); + ptosZ = (double*)&bufRecord[nb]; + nb+=npt*sizeof(double); + + mimaM = (double*)&bufRecord[nb]; + nb+=2*sizeof(double); + ptosM = (double*)&bufRecord[nb]; + nb+=npt*sizeof(double); + } + } + tc = npt*2; + break; + + case RPolyLine: + case Rpolygon: + mimC = (double*)&bufRecord[nb]; + nb +=2*sizeof(double); + maxC = (double*)&bufRecord[nb]; + nb +=2*sizeof(double); + numPart = *(int*)&bufRecord[nb]; + nb += sizeof(int); + npt = *(int*)&bufRecord[nb]; + nb += sizeof(int); + + part = (int*)&bufRecord[nb]; + nb += sizeof(int)*numPart; + ptos = (double*)&bufRecord[nb];//salta el tipo + nb+=sizeof(double)*2*npt; + if(nc>2) + { + if(nc<4) + { + mimaM = (double*)&bufRecord[nb]; + nb+=2*sizeof(double); + ptosM = (double*)&bufRecord[nb]; + nb+=npt*sizeof(double); + } + else + { + mimaZ = (double*)&bufRecord[nb]; + nb+=2*sizeof(double); + ptosZ = (double*)&bufRecord[nb]; + nb+=npt*sizeof(double); + + mimaM = (double*)&bufRecord[nb]; + nb+=2*sizeof(double); + ptosM = (double*)&bufRecord[nb]; + nb+=npt*sizeof(double); + } + } + tc = npt*2; + break; + default: + return false; + } + + return true; +} +//************************************************************************** +double* Fshape::get(int ip, int i) +{ + if(ip>numPart) + return NULL; + int nn = part[ip]*2+i*2; + if((nn+2)>tc) + return NULL; + return &ptos[nn]; +} +//************************************************************************** +double* Fshape::get( int i) +{ + if(i>=npt) + return NULL; + return &ptos[i*2]; +} +//************************************************************************** +int Fshape::getNp() +{ + return numPart; +} +//************************************************************************** +int Fshape::getType() +{ + return ReadType; +} +//************************************************************************** +int Fshape::getNcoord() +{ + return nc; +} +//************************************************************************** +int Fshape::getNPt(int ip) +{ + if(ip>numPart) + return -1; + if((numPart-1)>ip) + return part[ip+1]-part[ip]; + return npt - part[ip]; +} +//************************************************************************** +int Fshape::getNPt() +{ + return npt; +} +//************************************************************************** +bool Fshape::set(int type/*FshpReadType*/,int ncoord, Cb_file *file, Cb_file *file_shx) +{ + f_shx = file_shx; + memset(&head,0,sizeof(head)); + head.mima[0][0] = head.mima[0][1]= DBL_MAX; + head.mima[1][0] = head.mima[1][1]= -DBL_MAX; + ReadType=type; + nc = ncoord; + head.mimam[0]=head.mimam[1]=0; + head.mimaz[0]=head.mimam[1]=0; + head.ver =1000; + head.code = 9994; + //inv_4(&head.ver); + inv_4(&head.code); + head.nb = sizeof(head); + headr.nb = 0; + headr.nrec=0; + f = file; + if(nc<2 || nc>4) + return false; + switch(type) + { + case(Rpoint): + if(nc<=2) + head.tipo = Point; + else if(nc<=3) + head.tipo = PointM; + else + head.tipo = PointZ; + break; + case(RMpoint): + if(nc<=2) + head.tipo = MultiPoint; + else if(nc<=3) + head.tipo = MultiPointM; + else + head.tipo = MultiPointZ; + break; + case(RPolyLine): + if(nc<=2) + head.tipo = PolyLine; + else if(nc<=3) + head.tipo = PolyLineM; + else + head.tipo = PolyLineZ; + break; + case(Rpolygon): + if(nc<=2) + head.tipo = Polygon; + else if(nc<=3) + head.tipo = PolygonM; + else + head.tipo = PolygonZ; + break; + default: + return false; + } + headr.tipo = head.tipo; + if(f_shx && !f_shx->escribe(&head, sizeof(head))) + return false; + return (f->escribe(&head, sizeof(head))==TRUE); +} +//************************************************************************** +bool Fshape::grabaRecord(Cgarray *pts) +{ + int aux; + npt = pts->n/nc; + if(npt<=0) + return false; + + double mimaxr[2][2]; + mimaxr[0][0] = mimaxr[0][1]= DBL_MAX; + mimaxr[1][0] = mimaxr[1][1]= -DBL_MAX; + double mimaxZ[2]; + double mimaxM[2]; + mimaxZ[0] = mimaxM[0]= DBL_MAX; + mimaxZ[1] = mimaxM[1]= -DBL_MAX; + ptosM = NULL; + ptosZ = NULL; + int ii = 0; + switch(ReadType) + { + case(Rpoint): + { + headr.nb =sizeof(int)+sizeof(double)*nc; + headr.nb = headr.nb/2; + inv_4(&headr.nb); + for(int i=0; iescribe(&headr, sizeof(headr))) + return false; + inv_4(&headr.nrec); + aux = head.nb/2; + inv_4(&aux); + if(f_shx && !f_shx->escribe(&aux, sizeof(aux))) + return false; + head.nb+=sizeof(headr); + //graba offset + aux = headr.nb; + inv_4(&aux); + if(f_shx && !f_shx->escribe(&aux, sizeof(aux))) + return false; + ii = i*nc; + ptos = &(*pts)[ii]; + //pilla minimo y maximo + if(mimaxr[0][0]>ptos[0]) + mimaxr[0][0]=ptos[0]; + if(mimaxr[0][1]>ptos[1]) + mimaxr[0][1]=ptos[1]; + if(mimaxr[1][0]escribe(ptos, sizeof(double)*nc)) + return false; + head.nb+=sizeof(double)*nc; + } + } + break; + case(RMpoint): + { + headr.nb = sizeof(double)*nc*npt+sizeof(int); + headr.nb = inv_4(&headr.nb); + headr.nrec++; + headr.nrec=inv_4(&headr.nrec); + if(!f->escribe(&headr, sizeof(headr))) + return false; + headr.nrec=inv_4(&headr.nrec); + + aux = head.nb/2; + inv_4(&aux); + if(f_shx && !f_shx->escribe(&aux, sizeof(aux))) + return false; + head.nb+=sizeof(headr); + //graba offset + aux = headr.nb; + inv_4(&aux); + if(f_shx && !f_shx->escribe(&aux, sizeof(aux))) + return false; + if(nc>3) + { + ptosZ = &(*pts)[npt*3]; + ptosM = &(*pts)[npt*3]; + } + else if(nc>2) + { + ptosM = &(*pts)[npt*2]; + //mimam + } + + for(int i=0; iptos[0]) + mimaxr[0][0]=ptos[0]; + if(mimaxr[0][1]>ptos[1]) + mimaxr[0][1]=ptos[1]; + if(mimaxr[1][0]ptosM[i]) + mimaxM[0]=ptosM[i]; + if(mimaxM[1]ptosZ[i]) + mimaxZ[0]=ptosZ[i]; + if(mimaxZ[1]escribe(mimaxr, sizeof(double)*4)) + return false; + head.nb+=sizeof(double)*4; + + if(!f->escribe(&npt, sizeof(npt))) + return false; + head.nb+=sizeof(npt); + if(!f->escribe(&(*pts)[0], sizeof(double)*nc*npt)) + return false; + head.nb+=sizeof(double)*2*npt; + if(ptosZ) + { + if(!f->escribe(mimaxZ, sizeof(double)*2)) + return false; + head.nb+=sizeof(double)*2; + if(!f->escribe(ptosZ, sizeof(double)*npt)) + return false; + head.nb+=sizeof(double)*npt; + } + if(ptosM) + { + if(!f->escribe(mimaxM, sizeof(double)*2)) + return false; + head.nb+=sizeof(double)*2; + if(!f->escribe(ptosM, sizeof(double)*npt)) + return false; + head.nb+=sizeof(double)*npt; + } + } + break; + default: + return false; + } + //pilla coordenadas maximas y minimas totales del shp + if(head.mima[0][0]>mimaxr[0][0]) + head.mima[0][0]=mimaxr[0][0]; + if(head.mima[0][1]>mimaxr[0][1]) + head.mima[0][1]=mimaxr[0][1]; + if(head.mima[1][0] *pts, Cgarray*parts) +{ + int aux; + npt = pts->n/nc; + if(npt<=0) + return false; + + double mimaxr[2][2]; + mimaxr[0][0] = mimaxr[0][1]= DBL_MAX; + mimaxr[1][0] = mimaxr[1][1]= -DBL_MAX; + + double mimaxZ[2]; + double mimaxM[2]; + mimaxZ[0] = mimaxM[0]= DBL_MAX; + mimaxZ[1] = mimaxM[1]= -DBL_MAX; + ptosM = NULL; + ptosZ = NULL; + headr.tipo = head.tipo; + int ii = 0; + switch(ReadType) + { + case(RPolyLine): + case(Rpolygon): + { + headr.nrec++; + inv_4(&headr.nrec); + + headr.nb = sizeof(int)+sizeof(double)*4+2*sizeof(int)+ + +sizeof(int)*parts->n+sizeof(double)*2*npt; + if(nc>3) + { + ptosZ = &(*pts)[npt*3]; + ptosM = &(*pts)[npt*3]; + headr.nb+=2*(sizeof(double)*2+sizeof(double)*npt); + } + else if(nc>2) + { + headr.tipo = PolyLineZ; + ptosM = &(*pts)[npt*2]; + headr.nb+=sizeof(double)*2+sizeof(double)*npt; + //mimam + } + headr.nb = headr.nb/2; + inv_4(&headr.nb); + if(!f->escribe(&headr, sizeof(headr))) + return false; + inv_4(&headr.nrec); + inv_4(&headr.nb); + aux = head.nb/2; + inv_4(&aux); + if(f_shx && !f_shx->escribe(&aux, sizeof(aux))) + return false; + head.nb+=sizeof(headr); + //graba offset + aux = headr.nb; + inv_4(&aux); + if(f_shx && !f_shx->escribe(&aux, sizeof(aux))) + return false; + for(int i=0; iptos[0]) + mimaxr[0][0]=ptos[0]; + if(mimaxr[0][1]>ptos[1]) + mimaxr[0][1]=ptos[1]; + if(mimaxr[1][0]ptosM[i]) + mimaxM[0]=ptosM[i]; + if(mimaxM[1]ptosZ[i]) + mimaxZ[0] = ptosZ[i]; + if(mimaxZ[1]escribe(mimaxr, sizeof(double)*4)) + return false; + head.nb+=sizeof(double)*4; + if(!f->escribe(&parts->n, sizeof(parts->n))) + return false; + head.nb+=sizeof(parts->n); + if(!f->escribe(&npt, sizeof(npt))) + return false; + head.nb+=sizeof(npt); + if(!f->escribe(&(*parts)[0], sizeof(int)*parts->n)) + return false; + head.nb+=sizeof(int)*parts->n; + + if(!f->escribe(&(*pts)[0], sizeof(double)*2*npt)) + return false; + head.nb+=sizeof(double)*2*npt; + if(ptosZ) + { + if(!f->escribe(mimaxZ, sizeof(double)*2)) + return false; + head.nb+=sizeof(double)*2; + if(!f->escribe(ptosZ, sizeof(double)*npt)) + return false; + head.nb+=sizeof(double)*npt; + } + if(ptosM) + { + if(!f->escribe(mimaxM, sizeof(double)*2)) + return false; + head.nb+=sizeof(double)*2; + if(!f->escribe(ptosM, sizeof(double)*npt)) + return false; + head.nb+=sizeof(double)*npt; + } + } + break; + default: + return false; + } + //pilla coordenadas maximas y minimas totales del shp + if(head.mima[0][0]>mimaxr[0][0]) + head.mima[0][0]=mimaxr[0][0]; + if(head.mima[0][1]>mimaxr[0][1]) + head.mima[0][1]=mimaxr[0][1]; + if(head.mima[1][0]irAini()) + return false; + if(f_shx && !f_shx->irAini()) + return false; + head.nb = head.nb/2; + inv_4(&head.nb); + head.ver =1000; + head.code =9994; + inv_4(&head.code); + + if(!f->escribe(&head, sizeof(head))) + return false; + int auxi = head.nb; + head.nb = 100+headr.nrec*2*sizeof(int); + head.nb = head.nb/2; + inv_4(&head.nb); + if(f_shx && !f_shx->escribe(&head, sizeof(head))) + return false; + if(f_shx && !f_shx->irAfin()) + return false; + return (f->irAfin()== TRUE); +} +//************************************************************************** \ No newline at end of file diff --git a/Fshape.h b/Fshape.h new file mode 100644 index 0000000..ad3b35c --- /dev/null +++ b/Fshape.h @@ -0,0 +1,106 @@ +#pragma once +//clase para leer grabar shp +#ifndef Fshape_h +#define Fshape_h + +#include "base_head.h" +#include "garray.h" +#include "b_file.h" +#pragma pack(4) +typedef struct ShpHead +{ + int code; + int res[5]; + int nb; // tamaño en bytes del archivo + int ver; + int tipo; + double mima[2][2]; + double mimaz[2]; + double mimam[2]; +} ShpHead; +typedef struct ShpHeadReg +{ + int nrec; // nº del recor empezando en cero (en el file empiezan en 1) + int nb; // tamaño en bytes del record + int tipo; +} Shp_reg; + +#pragma pack(8) + +class UTILES_EXPORT Fshape +{ + Cgarray bufRecord; + //datos de archivo + ShpHead head; + ShpHeadReg headr; + double* mimC; //coordenadas mima + double* maxC; //coordenadas mima + double* mimaM; //coordenadas mima + double* mimaZ; //coordenadas mima + + double* ptos; //coordenadas de los puntos + double* ptosM; //coordenadas de los puntos + double* ptosZ; //coordenadas de los puntos + + + int ReadType; + int offserW; + int nc; // número de coordenadas que tiene cada punto + int npt;//numero total de puntos + int tc;//total de coordenadas de todos los puntos sumados + int *part;//partes del record + int numPart;//numero de partes + Cb_file *f;//puntero a archivo + Cb_file *f_shx;//puntero a archivo + +public: + enum FShapeType + { + NullShape=0, + Point=1, + PolyLine=3, + Polygon=5, + MultiPoint=8, + PointZ=11, + PolyLineZ=13, + PolygonZ=15, + MultiPointZ=18, + PointM=21, + PolyLineM=23, + PolygonM=25, + MultiPointM=28, + MultiPatch=31, + }; + enum FshpReadType + { + Rpoint=0, + RMpoint, + RPolyLine, + Rpolygon, + }; + + Fshape(void); + ~Fshape(void); + + //funciones de lectura-------------------------------- + bool leeHead(Cb_file *file); + bool LeeRecord(); + double* get(int i);//devuelve el punto i esimo de la parte ip + double* get(int ip, int i);//devuelve el punto i esimo de la parte ip + int getNp();//devuelve el total de partes + int getNPt(int ip);//devuelve el total de puntos de la parte ip + int getNPt();//devuelve el total de puntos de la parte ip + int getType();//devuelve tipo de objetos almacenados + int getNcoord();//devuelve numero de coordenadas por punto + //funciones de escritura------------------------------- + + bool set(int tipe/*FshpReadType*/,int ncoord, Cb_file *file,Cb_file *file_shx =0); + bool grabaRecord(Cgarray *pts); + bool grabaRecord(Cgarray *pts, Cgarray *parts); + bool FinGraba(); + + +private: + int inv_4(int *pb); +}; +#endif \ No newline at end of file diff --git a/GdataTable.cpp b/GdataTable.cpp new file mode 100644 index 0000000..9cac696 --- /dev/null +++ b/GdataTable.cpp @@ -0,0 +1,457 @@ +#include "StdAfx.h" +#include "GdataTable.h" +//*************************************************************************** +GdataTable::GdataTable(void) +{ +} +//*************************************************************************** +GdataTable::~GdataTable(void) +{ + delAll(); +} +//*************************************************************************** +int* GdataTable::getI(int row, int col) +{ + if(col>=colm.n || col<0) + return NULL; + if(colm[col].type !=Tint) + return NULL; + return &(*(Cgarray*)buf[col])[row]; +} +//*************************************************************************** +__int64* GdataTable::getI64(int row, int col) +{ + if(col>=colm.n || col<0) + return NULL; + if(colm[col].type !=Tint64) + return NULL; + return &(*(Cgarray<__int64>*)buf[col])[row]; +} +//*************************************************************************** +double* GdataTable::getD(int row, int col) +{ + if(col>=colm.n || col<0) + return NULL; + if(colm[col].type !=Tdouble) + return NULL; + return &(*(Cgarray*)buf[col])[row]; +} +//*************************************************************************** +bool* GdataTable::getBool(int row, int col) +{ + if(col>=colm.n || col<0) + return NULL; + if(colm[col].type !=Tbool) + return NULL; + return &(*(Cgarray*)buf[col])[row]; +} +//*************************************************************************** +char* GdataTable::getS(int row, int col) +{ + if(col>=colm.n || col<0) + return NULL; + if(colm[col].type !=Tstring) + return NULL; + return &(*(Cgarray*)buf[col])[row*colm[col].nb]; +} +//*************************************************************************** +void* GdataTable::getBin(int row, int col) +{ + if(col>=colm.n || col<0) + return NULL; + if(colm[col].type !=Tbin) + return NULL; + return (void*)&(*(Cgarray*)buf[col])[row*colm[col].nb]; +} +//*************************************************************************** +void* GdataTable::get(int row, int col) +{ + if(col>=colm.n || col<0) + return NULL; + switch(colm[col].type) + { + case(Tbool): + return(void*)&(*(Cgarray*)buf[col])[row]; + case(Tint): + return(void*)&(*(Cgarray*)buf[col])[row]; + case(Tdouble): + return(void*)&(*(Cgarray*)buf[col])[row]; + case(Tint64): + return(void*)&(*(Cgarray<__int64>*)buf[col])[row]; + case(Tstring): + case(Tbin): + return(void*)&(*(Cgarray*)buf[col])[row*colm[col].nb]; + default: + break; + } + return NULL; +} +//*************************************************************************** +bool GdataTable::addColm(char* name, int type, int size) +{ + colmName.add(name); + GdataTableColum inf; + void* c = NULL; + inf.flags=0; + inf.nb=size; + inf.type=type; + int nn =nRow(); + switch(type) + { + case(Tbool): + c = new Cgarray(); + if(!inf.nb) + inf.nb = sizeof(bool); + if(nn>0) + { + if(!((*(Cgarray*)c)+=nn)) + return false; + ((Cgarray*)c)->n = nn; + } + break; + case(Tint): + c = new Cgarray(); + if(!inf.nb) + inf.nb = sizeof(long); + if(nn>0) + { + if(!((*(Cgarray*)c)+=nn)) + return false; + ((Cgarray*)c)->n = nn; + } + break; + case(Tdouble): + c = new Cgarray(); + if(!inf.nb) + inf.nb = sizeof(double); + if(nn>0) + { + if(!((*(Cgarray*)c)+=nn)) + return false; + ((Cgarray*)c)->n = nn; + } + break; + case(Tint64): + c = new Cgarray<__int64>(); + if(!inf.nb) + inf.nb = sizeof(__int64); + if(nn>0) + { + if(!((*(Cgarray<__int64>*)c)+=nn)) + return false; + ((Cgarray<__int64>*)c)->n = nn; + } + break; + case(Tstring): + case(Tbin): + c = new Cgarray(); + if(nn>0) + { + if(!((*(Cgarray*)c)+=(nn*inf.nb))) + return false; + ((Cgarray*)c)->n = (nn*inf.nb); + } + break; + default: + return false; + } + if(!c) + return false; + if(!(buf+c)) + return false; + if(!(colm+inf)) + return false; + return true; +} +//*************************************************************************** +void GdataTable::delAll() +{ + for(int i =0; i*)buf[i]; + break; + case(Tint): + delete (Cgarray*)buf[i]; + break; + case(Tdouble): + delete (Cgarray*)buf[i]; + break; + case(Tint64): + delete (Cgarray<__int64>*)buf[i]; + break; + case(Tstring): + delete (Cgarray*)buf[i]; + break; + case(Tbin): + delete (Cgarray*)buf[i]; + break; + default: + break; + } + } + colm.n =0; + buf.n =0; + colmName.n_i =0; +} +//*************************************************************************** +void GdataTable::delAllRow() +{ + for(int i =0; i*)buf[i])->n=0; + break; + case(Tint): + ((Cgarray*)buf[i])->n=0; + break; + case(Tdouble): + ((Cgarray*)buf[i])->n=0; + break; + case(Tint64): + ((Cgarray<__int64>*)buf[i])->n=0; + break; + case(Tstring): + ((Cgarray*)buf[i])->n=0; + break; + case(Tbin): + ((Cgarray*)buf[i])->n=0; + break; + default: + break; + } + } +} +//*************************************************************************** +void GdataTable::removeColm(int i) +{ + switch(colm[i].type) + { + case(Tbool): + delete (Cgarray*)buf[i]; + break; + case(Tint): + delete (Cgarray*)buf[i]; + break; + case(Tdouble): + delete (Cgarray*)buf[i]; + break; + case(Tint64): + delete (Cgarray<__int64>*)buf[i]; + break; + case(Tstring): + delete (Cgarray*)buf[i]; + break; + case(Tbin): + delete (Cgarray*)buf[i]; + break; + default: + break; + } + + +} +//*************************************************************************** +int GdataTable::nRow() +{ + int i =0; + if(colm.n<=0) + return 0; + switch(colm[i].type) + { + case(Tbool): + return((Cgarray*)buf[i])->n; + case(Tint): + return((Cgarray*)buf[i])->n; + case(Tdouble): + return((Cgarray*)buf[i])->n; + case(Tint64): + return((Cgarray<__int64>*)buf[i])->n; + case(Tstring): + return((Cgarray*)buf[i])->n; + case(Tbin): + return((Cgarray*)buf[i])->n; + default: + break; + } + return -1; +} +//*************************************************************************** +int GdataTable::getType(int icol) +{ + if(icol<0 || icol>= colm.n) + return Tndef; + return colm[icol].type; +} +//*************************************************************************** +int GdataTable::getInd(char* colName) +{ + for(int i =0; i*)buf[i])+=nrow)) + return false; + (*(Cgarray*)buf[i]).n+=nrow; + break; + case(Tint): + if(!((*(Cgarray*)buf[i])+=nrow)) + return false; + (*(Cgarray*)buf[i]).n+=nrow; + break; + case(Tdouble): + if(!((*(Cgarray*)buf[i])+=nrow)) + return false; + (*(Cgarray*)buf[i]).n+=nrow; + break; + case(Tint64): + if(!((*(Cgarray<__int64>*)buf[i])+=nrow)) + return false; + (*(Cgarray<__int64>*)buf[i]).n+=nrow; + break; + case(Tstring): + if(!((*(Cgarray*)buf[i])+=(nrow*colm[i].nb))) + return false; + (*(Cgarray*)buf[i]).n+=(nrow*colm[i].nb); + break; + case(Tbin): + if(!((*(Cgarray*)buf[i])+=(nrow*colm[i].nb))) + return false; + (*(Cgarray*)buf[i]).n+=(nrow*colm[i].nb); + break; + default: + return false; + + } + } + return true; +} +//*************************************************************************** +void GdataTable::removeRow(int i) +{ + for(int i =0; i*)buf[i]).remove(i); + break; + case(Tint): + (*(Cgarray*)buf[i]).remove(i); + break; + case(Tdouble): + (*(Cgarray*)buf[i]).remove(i); + break; + case(Tint64): + (*(Cgarray<__int64>*)buf[i]).remove(i); + + break; + case(Tstring): + (*(Cgarray*)buf[i]).remove(i, colm[i].nb); + break; + case(Tbin): + (*(Cgarray*)buf[i]).remove(i, colm[i].nb); + break; + default: + break; + } + } +} +//*************************************************************************** +int GdataTable::nColm() +{ + return colm.n; +} +//*************************************************************************** +int GdataTable::getSize( int icol ) +{ + if(icol<0 || icol>colm.n) + return -1; + return colm[icol].nb; +} +//*************************************************************************** +char* GdataTable::getName( int icol ) +{ + if(icol<0 || icol>colm.n) + return 0; + return colmName.get(icol); +} +//*************************************************************************** +bool GdataTable::addMemRow( int nrow ) +{ + for(int i =0; i*)buf[i])+=nrow)) + return false; + break; + case(Tint): + if(!((*(Cgarray*)buf[i])+=nrow)) + return false; + break; + case(Tdouble): + if(!((*(Cgarray*)buf[i])+=nrow)) + return false; + break; + case(Tint64): + if(!((*(Cgarray<__int64>*)buf[i])+=nrow)) + return false; + break; + case(Tstring): + if(!((*(Cgarray*)buf[i])+=(nrow*colm[i].nb))) + return false; + break; + case(Tbin): + if(!((*(Cgarray*)buf[i])+=(nrow*colm[i].nb))) + return false; + break; + default: + return false; + + } + } + return true; +} +//*************************************************************************** +int GdataTable::getSizeASCII( int icol ) +{ + if(!colm[icol].nb) + { + switch(colm[icol].type) + { + case(Tbool): + return 1; + case(Tint): + return 4; + case(Tdouble): + return 8; + case(Tint64): + return 8; + case(Tbin): + case(Tstring): + return colm[icol].nb; + default: + return -1; + } + } + else + return colm[icol].nb; +} +//*************************************************************************** \ No newline at end of file diff --git a/GdataTable.h b/GdataTable.h new file mode 100644 index 0000000..8c472f4 --- /dev/null +++ b/GdataTable.h @@ -0,0 +1,73 @@ +#pragma once +#ifndef GdataTable_h +#define GdataTable_h +//tabla de datos generica +//tabla con nombre de columnas +#include "base_head.h" +#include "garray.h" +#include "StrArray.h" +class UTILES_EXPORT GdataTableColum +{ +public: + int type;//tipo de dato + int nb;//numero de bytes de informacion + int flags; +}; + +class UTILES_EXPORT GdataTable +{ + Cgarraybuf; //array de Garray de datos + Cgarraycolm; //datos de columnas + StrArray colmName; //nombre de columnas + +public: + enum TypedataTable + { + Tndef=0, + Tbool, + Tint, + Tdouble, + Tint64, + Tstring, + Tbin, + Tntip + }; + GdataTable(void); + ~GdataTable(void); + + //funciones de lectura y set------------ + int getType(int icol); + int getInd(char* colName); + int nRow(); + int nColm(); + int getSize(int icol); + int getSizeASCII(int icol); + + char* getName(int icol); + int* getI(int row, int colm); + __int64* getI64(int row, int colm); + double* getD(int row, int colm); + char* getS(int row, int colm); + void* getBin(int row, int colm); + bool* getBool(int row, int col); + + void* get(int row, int colm); + //funciones de modificacion------------- + + //adicionar----------------------------- + bool addColm(char* name, int type, int size=0); + bool addRow(int nrow); + bool addMemRow(int nrow); + //borrado------------------------------- + void delAllRow();//borra todas las filas + void delAll();//borra todo + + void removeRow(int i); + void removeColm(int i); + + //ajusta memoria + void clear(); + //funciones auxiliares-------------------- +private: +}; +#endif \ No newline at end of file diff --git a/GeometryFunction.cpp b/GeometryFunction.cpp new file mode 100644 index 0000000..3ba6a59 --- /dev/null +++ b/GeometryFunction.cpp @@ -0,0 +1,609 @@ +#include "StdAfx.h" +#include "GeometryFunction.h" +#include +#include +//***************************************************************************************** +double GeometryFunction::Dist2d(double*p1, double*p2) +{ + return sqrt(Poten(p1[0]-p2[0])+Poten(p1[1]-p2[1])); +} +//***************************************************************************************** +double GeometryFunction::LongLine2d(SetPtsR *line) +{ + int nn = line->getNumberPtos(); + double res =0; + double *p1,*p2; + if(nn<2) + return res; + p1 = line->getPto(0); + for(int i =1; igetPto(i); + res+=Dist2d(p1,p2); + p1=p2; + } + return res; +} +//***************************************************************************************** +void GeometryFunction::CompMima(double dst[2][3], SetPtsR* pts) +{ + dst[0][0] = dst[0][1]= DBL_MAX; + dst[1][0] = dst[1][1]= -DBL_MAX; + for( int i = pts->getNumberPtos()-1; i>0; i--) + { + double *p = pts->getPto(i); + if(dst[0][0]>p[0]) + dst[0][0]=p[0]; + if(dst[0][1]>p[1]) + dst[0][1]=p[1]; + if(dst[1][0]* GeometryFunction::EnvConvex(SetPtsR* pts, Cgarray* dst) +{ + return dst; +} +//***************************************************************************************** +double GeometryFunction::Dpline(double* l1, double *l2, double *p, double *lamb) +{ + double aux = Poten( l2[0] - l1[0] ) + + Poten( l2[1] - l1[1] ); + if ( aux < 1.e-20 ) + aux = 0.; + else + { + aux = ((l2[0] - l1[0] ) * ( p[0] - l1[0] ) + ( l2[1] - l1[1] ) * ( p[1] - l1[1]))/ aux; + } + if(lamb) + *lamb = aux; + return sqrt( Poten(p[0]-l1[0]-aux*(l2[0]-l1[0]))+ + Poten(p[1] - l1[1] - aux * (l2[1] - l1[1]))); +} +//***************************************************************************************** +double GeometryFunction::DpSeg(double* s1, double *s2, double *p, double *lamb) +{ + double aux; + double dis=Dpline(s1,s2,p,&aux); + if(aux<0)//distancia en s1 + { + aux =0; + dis = Dist2d(s1, p); + } + if(aux>1)//distancia en s2 + { + aux =1; + dis = Dist2d(s2, p); + } + if(lamb) + *lamb = aux; + return dis; +} +//***************************************************************************************** +double GeometryFunction::DisPtoLine(SetPtsR* line, double*p, int* idpto, double *lamb) +{ + int nn = line->getNumberPtos(); + double dis = DBL_MAX; + int ii = -1, ip; + double l, laux, disa; + double *p1,*p2; + if(nn<2) + { + if(lamb) + *lamb = 0; + if(idpto) + *idpto=0; + return dis; + } + + p1 = line->getPto(0); + ip =0; + for(int i =1; igetPto(i); + disa=DpSeg(p1,p2,p,&laux); + if(disagetNumberPtos(); + if(nn<=0) + return 0; + if(distTot&& *distTotgetPto(nn-1); + for(int i=0; i<3; i++) + dst[i]=p1[i]; + return dst; + } + p1 = line->getPto(0); + for(int ip =1; ipgetPto(ip); + disAct= Dist2d(p1,p2); + if(disAct>= dis && disAct>0) + { + //encontrado segmento limite de linea + double l =dis/disAct; + for(int ii=0; ii<3; ii++) + dst[ii]=p1[ii]+l*(p2[ii]-p1[ii]); + return dst; + } + dis-=disAct; + p1=p2; + } + for(int i=0; i<3; i++) + dst[i]=p1[i]; + return dst; + +} +//***************************************************************************************** +bool GeometryFunction::DivLine(SetPtsR* line, SetPtsW* ldst1, SetPtsW* ldst2, double dis) +{ + int nn = line->getNumberPtos(); + double disAct =0; + double *p1,*p2; + double pp[3]; + double l=-1; + if(nn<2) + return false; + p1 = line->getPto(0); + if(!ldst1->addPto(p1)) + return false; + int i =0; + for(i =1; igetPto(i); + disAct= Dist2d(p1,p2); + if(disAct>=dis && disAct>0) + { + //encontrado segmento limite de linea + l =dis/disAct; + for(int ii=0; ii<3; ii++) + pp[ii]=p1[ii]+l*(p2[ii]-p1[ii]); + if(l>0) + { + if(!ldst1->addPto(pp)) + return false; + } + break; + } + dis-=disAct; + if(!ldst1->addPto(p2)) + return false; + p1=p2; + } + if(l<0) + return false; + //rellena segunda linea + if(l<1) + { + if(!ldst2->addPto(pp)) + return false; + } + if(!ldst2->addPto(p2)) + return false; + i++; + for(; igetPto(i); + if(!ldst2->addPto(p2)) + return false; + } + return true; +} +//***************************************************************************************** +bool GeometryFunction::DivLine(SetPtsR* line, SetPtsWBuilder *builder, double dist) +{ + int nn = line->getNumberPtos(); + double disAct =0; + double *p1,*p2; + double pp[3], pp1[3]; + double l=-1; + double dis = dist; + SetPtsW *ldst; + if(nn<2) + return false; + ldst =builder->build(); + p1 = line->getPto(0); + if(!ldst->addPto(p1)) + return false; + int i =0; + for(i =1; igetPto(i); + disAct= Dist2d(p1,p2); + if(disAct>=dis && disAct>0) + { + for(int ii=0; ii<3; ii++) + pp1[ii]=p1[ii]; + while(disAct>dis) + { + //encontrado segmento limite de linea + l =dis/disAct; + for(int ii=0; ii<3; ii++) + pp[ii]=pp1[ii]+l*(p2[ii]-pp1[ii]); + //añade punto en el que se alcanza la distancia + if(l>0) + { + if(!ldst->addPto(pp)) + return false; + } + if(i==nn-1 && l==1) + { + dis =0; + break; + } + //se pide otra linea + ldst =builder->build(); + for(int ii=0; ii<3; ii++) + pp1[ii]=pp[ii]; + if(l<1) + { + if(!ldst->addPto(pp1)) + return false; + } + + disAct-=dis; + dis =dist; + } + + } + else + dis-=disAct; + if(!ldst->addPto(p2)) + return false; + p1=p2; + } + + return true; +} +//************************************************************************************************************************** +/* +* Devuelve el ángulo entre v1 y v2 +*/ +double GeometryFunction::AngVect(double v1[2], double v2[2]) +{ + double res = sqrt(v1[0] * v1[0] + v1[1] * v1[1]) * + sqrt(v2[0] * v2[0] + v2[1] * v2[1]); + if(res==0) + return 0; + res = (v1[0] * v2[0] + v1[1] * v2[1]) / res; + if (res > 1) + res = 1; + if (res < -1) + res = -1; + return acos(res); +} +//************************************************************************************************************************** +/* +* Calcula si el punto p está a la derecha del vector definido por los dos puntos de ptos +* Se calcula el producto escalar de los dos vectores +*/ +bool GeometryFunction::IsDer(SetPtsR* ptos, double *p, int ip1, int ip2) +{ + double d; + double *p1, *p2; + p1=ptos->getPto(ip1); + p2=ptos->getPto(ip2); + + d = (p2[0] - p1[0])*(p[1] - p1[1]) - + (p2[1] - p1[1])*(p[0] - p1[0]); + + return d< 0; +} +//***************************************************************************************** +//Siempre se le debe llamar de forma que line1 sea de menor longitud que line2 +//partiendo de line1 y calculando la distancia de puntos equidistantes l_avan a los puntos +//más cercanos de line2 +double GeometryFunction::DisMedLines( SetPtsR* line1, SetPtsR* line2, double l_avan, double *desv/*=NULL*/) +{ + int n; + double l_parc, long1, dd, dd2,dis; + double pt1[3]; + + long1=LongLine2d(line1); + if(l_avan>long1) + l_avan=long1; + n=(int)(long1/l_avan); + l_parc=0; + dd=dd2=0; + while(l_parcgetNumberPtos(); + while(igetPto(i); + dis = DisPtoLine(line2,p); + dd+=dis/n; + dd2+=Poten(dis)/n; + i++; + } + + if(desv) + *desv=sqrt(dd2-Poten(dd)); + return dd; +} +//************************************************************************************* +/** + * Devuelve el prodcuto escalar de los vectores formados por los dos puntos 'ptos1' + * y los dos en 'ptos2' + */ +double GeometryFunction::ProdEscalar(SetPtsR* line1, SetPtsR* line2) +{ + double p; + p=0; + + for(int i=0;i<3; i++) + p+=(line1->getPto(1)[i]-line1->getPto(0)[i])*(line2->getPto(1)[i]-line2->getPto(0)[i]); + + return p; +} +//***************************************************************************************** +SetPtsW * GeometryFunction::GetNPrimePtos( SetPtsR* line, SetPtsW *ldst, int nptos, double dist, BOOL avanza ) +{ + int nn = line->getNumberPtos(); + double disAct =0; + double *p1,*p2; + double pp[3]; + double paux1[3]; + double l=-1; + double dis = dist; + int i; + if(nn<2) + return NULL; + if(avanza) + p1 = line->getPto(0); + else + p1 = line->getPto(nn-1); + + if(!ldst->addPto(p1)) + return NULL; + nptos--; + int ip =0; + for(ip =1; ip0; ip++) + { + if(avanza) + i = ip; + else + i = nn-1-ip; + p2 = line->getPto(i); + disAct= Dist2d(p1,p2); + if(disAct>=dis && disAct>0) + { + for(int ii=0; ii<3; ii++) + paux1[ii]=p1[ii]; + while(disAct>=dis && nptos>0) + { + + + //encontrado segmento limite de linea + l =dis/disAct; + for(int ii=0; ii<3; ii++) + pp[ii]=paux1[ii]+l*(p2[ii]-paux1[ii]); + + + if(!ldst->addPto(pp)) + return NULL; + nptos--; + for(int ii=0; ii<3; ii++) + paux1[ii]=pp[ii]; + disAct -=dis; + dis =dist; + } + } + else + dis-=disAct; + p1=p2; + } + + return ldst; +} +//***************************************************************************************** +double GeometryFunction::DisInLine( SetPtsR* linesrc, int ip, double lamb ) +{ + double dis=0; + double *p1, *p2, pp[3]; + if(ip<0) + return -1; + p1=linesrc->getPto(0); + if(!p1) + return -1; + for(int i=1; i<=ip; i++) + { + p2 = linesrc->getPto(i); + if(!p2) + return -1; + dis+=Dist2d(p1,p2); + p1=p2; + } + p2=linesrc->getPto(ip+1); + if(!p2) + return -1; + pp[2]=0; + for(int i=0; i<2;i++) + pp[i]=p1[i]+(p2[i]-p1[i])*lamb; + + dis+=Dist2d(p1,pp); + + return dis; +} +//***************************************************************************************** +double *GeometryFunction::PtInLine( SetPtsR* linesrc, int ip, double lamb, double *pp ) +{ + double *p1, *p2; + if(ip<0) + return 0; + if(!pp) + return 0; + + p1=linesrc->getPto(ip); + if(!p1) + return 0; + p2=linesrc->getPto(ip+1); + if(!p2) + return 0; + pp[2]=0; + for(int i=0; i<2;i++) + pp[i]=p1[i]+(p2[i]-p1[i])*lamb; + + return pp; +} +//***************************************************************************************** +double* GeometryFunction::intersecLine(double* l11, double *l12, double* l21, double *l22, double *p_inters) +{ + double v1[2], v2[2], a[2][2], b[2]; + //calcula vectores directores----------- + for(int i =0; i<2; i++) + { + v1[i] = l12[i]-l11[i]; + v2[i] = l22[i]-l21[i]; + } + //calculo de matriz de coeficientes-------- + a[0][0] = v1[1]; + a[0][1] = -v1[0]; + a[1][0] = v2[1]; + a[1][1] = -v2[0]; + //calculo terminos independientes----------- + b[0]=l11[0]*v1[1]-l11[1]*v1[0]; + b[1]=l21[0]*v2[1]-l21[1]*v2[0]; + //calculo determinante----------------------- + double det = a[0][0]*a[1][1]-a[1][0]*a[0][1]; + if(det == 0) + return NULL;//lineas son paralelas + p_inters[0]= (b[0]*a[1][1]-a[0][1]*b[1])/det; + p_inters[1]= (a[0][0]*b[1]-b[0]*a[1][0])/det; + return p_inters; +} +//***************************************************************************************** +double GeometryFunction::DLineSeg( double* l1, double *l2, double* s1, double *s2, double *lambl,double *lambs, bool*paralelos ) +{ + double p[2]; + double d1, d2, lamb2; + *lambs = 0; + if(paralelos) + *paralelos = false; + d1 =Dpline(l1,l2,s1,lambl); + if(d1 <=0 || !intersecLine(l1,l2,s1,s2,p)) + { + if(d1>0 && paralelos) + *paralelos = true; + return d1; + } + d2 = DpSeg(s1,s2,p, &lamb2); + if(d2lamb2) + *lambl = -*lambl; + if(d1<=0) + return d1; + } + d2 = Dpline(l1,l2,s2, &lamb2); + if(d21) + { + *lamd1 =1; + return DpSeg(s21,s22,s12,lamd2); + } + return dl;//se alcanza en la linea +} +//***************************************************************************************** +double GeometryFunction::DplineSeg( SetPtsR* line1, double* s1, double *s2,int *n, double *lamd1,double *lamb2 ) +{ + double d=(double) 1.e+30, d1, l1, l2; + + double *p1,*p2; + int nn = line1->getNumberPtos(); + if(nn<=0) + return d; + p1 = line1->getPto(0); + for(int i =1; igetPto(i); + d1 = DsegSeg(p1,p2,s1,s2,&l1,&l2); + if(d1* EnvConvex(SetPtsR* pts, Cgarray* dst); + //distancia de un punto a una linea + static double DisPtoLine(SetPtsR* line, double*p, int* idpto=NULL, double *lamb=NULL); + //distancia media entre dos líneas + static double DisMedLines( SetPtsR* line1, SetPtsR* line2, double *desv=NULL); + static double DisMedLines( SetPtsR* line1, SetPtsR* line2, double l_avan, double *desv=NULL); + //parte una linea en 2 + static bool DivLine(SetPtsR* linesrc, SetPtsW* ldst1, SetPtsW* ldst2, double dis); + //dado el ip y el lamb da la distancia desde el principio de la linea + static double DisInLine(SetPtsR* linesrc, int ip, double lamb); + //dado el ip y el lamb da la distancia desde el punto contenido en la línea + static double *PtInLine( SetPtsR* linesrc, int ip, double lamb , double *pp ); + //devuelve los nptos primeros puntos de line, equiespaciados dis + //si avanza, los coge del principio, si no, del final + static SetPtsW *GetNPrimePtos(SetPtsR* line, SetPtsW *ldst, int nptos, double dis, BOOL avanza); + + //divide la linea en partes equidistantes + static bool DivLine(SetPtsR* line, SetPtsWBuilder *manager, double dis); + + //devuelve el punto que esta en la polilinea a una distancia dist + static double* GetPto(SetPtsR* line, double dis, double *dst, double *distTot = NULL); + + static double ang_vect_ptos(double (*ptos1)[][3], double (*ptos2)[][3]); + + //devuelve el angulo que forman los 2 vectores + static double AngVect(double v1[2], double v2[2]); + //dice si el punto p esta a la derecha de la linea que forman los puntos ip1 y ip2 + static bool IsDer(SetPtsR* ptos, double *p, int ip1, int ip2); + static double ProdEscalar(SetPtsR* line1, SetPtsR* line2); + + //funcion auxiliar potencia + static inline double Poten(double bas, int exp = 2) + { + if(exp<=0) + return 0; + double res = bas; + while(exp>1) + { + res = res * bas; + exp--; + } + return res; + } +}; + +#endif \ No newline at end of file diff --git a/IaDataTable.cpp b/IaDataTable.cpp new file mode 100644 index 0000000..5473b62 --- /dev/null +++ b/IaDataTable.cpp @@ -0,0 +1,294 @@ +#include "StdAfx.h" +#include "IaDataTable.h" +#include "CartoBase.h" +#include "Fdbf.h" +//*************************************************************************** +IaDataTable::IaDataTable(void) +{ + auxnrow=-1; + auxref =-1; + auxref = auxc=-1; + +} +//*************************************************************************** +IaDataTable::~IaDataTable(void) +{ +} +//*************************************************************************** +void* IaDataTable::IaGet( int refEnt ) +{ + return NULL; +} +//*************************************************************************** +void IaDataTable::CBSet( CartoBase* cb ) +{ + _cb = cb; +} +//*************************************************************************** +void IaDataTable::IaRemove( int refEnt ) +{ + int icol = RefIndex[refEnt]; + if(icol<0) + return; + removeRow(RefIndex[refEnt]); + RefIndex[refEnt]=-1; + rowIndex[icol] = -1; +} +//*************************************************************************** +void IaDataTable::IaRemoveAll() +{ + RefIndex.clear(); + rowIndex.clear(); + delAll(); +} +//*************************************************************************** +void IaDataTable::IaAdd( int refEnt ) +{ + if(!addRow(1)) + { + RefIndex[refEnt] = -1; + return; + } + int iRow=nRow()-1; + RefIndex[refEnt]=iRow; + rowIndex[iRow] = refEnt; +} +//*************************************************************************** +bool IaDataTable::IaSet( int nrow, int ncolm ) +{ + IaRemoveAll(); + auxnrow = nrow; + auxcolm =ncolm; + return true; +} +//*************************************************************************** +bool IaDataTable::IaSetColm( int icol, char* name, BYTE type, int size ) +{ + int t; + switch(type) + { + case(DBF_TYPE_DATA_STR): + t = GdataTable::Tstring; + break; + case(DBF_TYPE_DATA_I64): + t = GdataTable::Tint64; + break; + case(DBF_TYPE_DATA_D): + t = GdataTable::Tdouble; + break; + case(DBF_TYPE_DATA_BOOL): + t = GdataTable::Tbool; + break; + case(DBF_TYPE_DATA_BIN): + t = GdataTable::Tbin; + break; + case(DBF_TYPE_DATA_I): + t = GdataTable::Tint; + break; + default: + return false; + } + bool res = addColm(name,t,size); + if(res && auxcolm>0 && nColm()>= auxcolm) + { + res = addMemRow(auxnrow); + auxnrow =0; + } + return res; +} +//*************************************************************************** +bool IaDataTable::IaAddVal( int refEnt, int icol, int v ) +{ + int _nrow; + if(auxnrow>=0) + _nrow =RefIndex[refEnt]; + else + _nrow = RefIndex[refEnt]; + int* vv = getI(auxnrow,icol); + if(vv) + *vv = v; + return vv!= NULL; +} +//*************************************************************************** +bool IaDataTable::IaAddVal( int refEnt, int icol, double v ) +{ + int _nrow; + if(auxnrow>=0) + _nrow =RefIndex[refEnt]; + else + _nrow = RefIndex[refEnt]; + double* vv = getD(_nrow,icol); + if(vv) + *vv = v; + return vv!= NULL; +} +//*************************************************************************** +bool IaDataTable::IaAddVal( int refEnt, int icol, __int64 v ) +{ + int _nrow; + if(auxnrow>=0) + _nrow =RefIndex[refEnt]; + else + _nrow = RefIndex[refEnt]; + __int64* vv = getI64(_nrow,icol); + if(vv) + *vv = v; + return vv!= NULL; +} +//*************************************************************************** +bool IaDataTable::IaAddVal( int refEnt, int icol, char* v ) +{ + int _nrow; + if(auxnrow>=0) + _nrow =RefIndex[refEnt]; + else + _nrow = RefIndex[refEnt]; + char* vv = getS(_nrow,icol); + if(vv) + strcpy(vv,v); + return vv!= NULL; +} +//*************************************************************************** +bool IaDataTable::IaAddVal( int refEnt, int icol, void* v ) +{ + int _nrow; + if(auxnrow>=0) + _nrow =RefIndex[refEnt]; + else + _nrow = RefIndex[refEnt]; + void* vv = getBin(_nrow,icol); + if(vv) + memcpy(vv,v, getSize(icol)); + return vv!= NULL; +} +//*************************************************************************** +bool IaDataTable::IaFinRow( int refEnt ) +{ + auxnrow++; + return true; +} +//*************************************************************************** +bool IaDataTable::IaFinR() +{ + auxnrow=-1; + return true; +} +//*************************************************************************** +bool IaDataTable::IaGetSize(int *ncolm ) +{ + *ncolm =nColm(); + return true; +} +//*************************************************************************** +#define MAX_NDECIMALS 10; +bool IaDataTable::IaGetColm( int icol, char* name, BYTE *type, int *size, int*ndecimal ) +{ + //pilla tipo---------------------- + static BYTE t[GdataTable::Tntip]={0,DBF_TYPE_DATA_BOOL,DBF_TYPE_DATA_I, DBF_TYPE_DATA_D,DBF_TYPE_DATA_I64, DBF_TYPE_DATA_STR, DBF_TYPE_DATA_BIN } ; + *type = t[getType(icol)]; + *ndecimal = MAX_NDECIMALS; + //copia segura de nombre------------------ + int i =0; + char *st =getName(icol); + for(; i<10; i++) + { + if(!st[i]) + break; + name[i]=st[i]; + } + name[i]=0; + *size = getSizeASCII(icol); + return *size>0; +} +//*************************************************************************** +bool IaDataTable::IaGetVal( int refEnt, int icol, int* v ) +{ + int irow; + if(auxref == refEnt) + irow = auxc; + else + { + irow = RefIndex[refEnt]; + auxref = refEnt; + auxc = irow; + } + if(irow<0) + return false; + *v = *getI(irow,icol); + return true; +} +//*************************************************************************** +bool IaDataTable::IaGetVal( int refEnt, int icol, double* v ) +{ + int irow; + if(auxref == refEnt) + irow = auxc; + else + { + irow = RefIndex[refEnt]; + auxref = refEnt; + auxc = irow; + } + if(irow<0) + return false; + *v = *getD(irow,icol); + return true; +} +//*************************************************************************** +bool IaDataTable::IaGetVal( int refEnt, int icol, __int64* v ) +{ + int irow; + if(auxref == refEnt) + irow = auxc; + else + { + irow = RefIndex[refEnt]; + auxref = refEnt; + auxc = irow; + } + if(irow<0) + return false; + *v = *getI64(irow,icol); + return true; +} +//*************************************************************************** +bool IaDataTable::IaGetVal( int refEnt, int icol, char** v ) +{ + int irow; + if(auxref == refEnt) + irow = auxc; + else + { + irow = RefIndex[refEnt]; + auxref = refEnt; + auxc = irow; + } + if(irow<0) + return false; + *v= getS(irow,icol); + return true; +} +//*************************************************************************** +bool IaDataTable::IaGetVal( int refEnt, int icol, void** v ) +{ + int irow; + if(auxref == refEnt) + irow = auxc; + else + { + irow = RefIndex[refEnt]; + auxref = refEnt; + auxc = irow; + } + if(irow<0) + return false; + *v= getBin(irow,icol); + return true; +} +//*************************************************************************** +bool IaDataTable::IaFinW() +{ + auxref = auxc=-1; + return true; +} +//*************************************************************************** \ No newline at end of file diff --git a/IaDataTable.h b/IaDataTable.h new file mode 100644 index 0000000..6199b1d --- /dev/null +++ b/IaDataTable.h @@ -0,0 +1,45 @@ +#pragma once + +#ifndef IaDataTable_h +#define IaDataTable_h +#include "gdatatable.h" +#include "base_head.h" +#include "CartoBaseDef.h" +#include +class CartoBase; +//tabla de datos para albergar informacion asiciada generica (diseñada para el cartobase) +class UTILES_EXPORT IaDataTable : + public GdataTable, public DataIaCartoBase +{ + std::map RefIndex;//indexado por referencias; + std::map rowIndex;//indexado por filas; + CartoBase* _cb; + int auxnrow,auxcolm,auxref,auxc; +public: + IaDataTable(void); + ~IaDataTable(void); + + virtual void* IaGet( int refEnt ); + virtual void CBSet( CartoBase* cb ); + virtual void IaRemove( int refEnt ); + virtual void IaRemoveAll(); + virtual void IaAdd( int refEnt ); + virtual bool IaSet( int nrow, int ncolm ); + virtual bool IaSetColm( int icol, char* name, BYTE type, int size ); + virtual bool IaAddVal( int refEnt, int icol, int v ); + virtual bool IaAddVal( int refEnt, int icol, double v ); + virtual bool IaAddVal( int refEnt, int icol, __int64 v ); + virtual bool IaAddVal( int refEnt, int icol, char* v ); + virtual bool IaAddVal( int refEnt, int icol, void* v ); + virtual bool IaFinRow( int refEnt ); + virtual bool IaFinR(); + virtual bool IaGetSize( int *ncolm ); + virtual bool IaGetColm( int icol, char* name, BYTE *type, int *size, int*ndecimal ); + virtual bool IaGetVal( int refEnt, int icol, int* v ); + virtual bool IaGetVal( int refEnt, int icol, double* v ); + virtual bool IaGetVal( int refEnt, int icol, __int64* v ); + virtual bool IaGetVal( int refEnt, int icol, char** v ); + virtual bool IaGetVal( int refEnt, int icol, void** v ); + virtual bool IaFinW(); +}; +#endif \ No newline at end of file diff --git a/ManagerDbfGdataTable.cpp b/ManagerDbfGdataTable.cpp new file mode 100644 index 0000000..3ada239 --- /dev/null +++ b/ManagerDbfGdataTable.cpp @@ -0,0 +1,229 @@ +#include "StdAfx.h" +#include "ManagerDbfGdataTable.h" +#include "GdataTable.h" +//*************************************************************************** + +ManagerDbfGdataTable::ManagerDbfGdataTable(void) +{ + _dt = NULL; +} +//*************************************************************************** + +ManagerDbfGdataTable::~ManagerDbfGdataTable(void) +{ +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfSet( int nrow, int ncolm ) +{ + _dt->delAll(); + _nrow = nrow; + _ncolm = ncolm; + return true; +} +//*************************************************************************** +bool ManagerDbfGdataTable::AddCol( char* path, char* name, BYTE type,IAddColDbf *dt, int size) +{ + GdataTable tb; + + if(!LeeDbf(path, &tb)) + return false; + int ic=tb.getInd(name); + + if(ic<0) + { + //la crea + if(!tb.addColm(name,type,size)) + return false; + ic=tb.nColm()-1; + } + for(int i=0;isetData(i, tb.get(i,ic)); + } + + if(!grabaDbf(path,&tb)) + return false; + + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfSetColm( char* name, BYTE type, int size ) +{ + int t; + switch(type) + { + case(DBF_TYPE_DATA_STR): + size++; + t = GdataTable::Tstring; + break; + case(DBF_TYPE_DATA_I64): + t = GdataTable::Tint64; + break; + case(DBF_TYPE_DATA_D): + t = GdataTable::Tdouble; + break; + case(DBF_TYPE_DATA_BOOL): + t = GdataTable::Tbool; + break; + case(DBF_TYPE_DATA_BIN): + t = GdataTable::Tbin; + break; + case(DBF_TYPE_DATA_I): + t = GdataTable::Tint; + break; + default: + return false; + } + bool res = _dt->addColm(name,t,size); + if(res && _nrow>0 && _dt->nColm()>= _ncolm) + { + res = _dt->addRow(_nrow); + _nrow =0; + } + return res; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfaddVal( int icol, int v ) +{ + int* vv = _dt->getI(_nrow,icol); + if(vv) + *vv = v; + return vv!= NULL; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfaddVal( int icol, double v ) +{ + double* vv = _dt->getD(_nrow,icol); + if(vv) + *vv = v; + return vv!= NULL; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfaddVal( int icol, __int64 v ) +{ + __int64* vv = _dt->getI64(_nrow,icol); + if(vv) + *vv = v; + return vv!= NULL; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfaddVal( int icol, char* v ) +{ + char* vv = _dt->getS(_nrow,icol); + if(vv) + strcpy(vv,v); + return vv!= NULL; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfaddVal( int icol, void* v ) +{ + void* vv = _dt->getBin(_nrow,icol); + if(vv) + memcpy(vv,v,_dt->getSize(icol)); + return vv!= NULL; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfFinRow() +{ + _nrow++; + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfFinR() +{ + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfGet( int *nrow, int *ncolm ) +{ + *nrow = _dt->nRow(); + *ncolm = _dt->nColm(); + _nrow =0; + return true; +} +//*************************************************************************** +#define MAX_NDECIMALS 10; +bool ManagerDbfGdataTable::DbfGetColm(int icolm, char* name, BYTE *type, int *size, int*ndecimal ) +{ + //pilla tipo---------------------- + static BYTE t[GdataTable::Tntip]={0,DBF_TYPE_DATA_BOOL,DBF_TYPE_DATA_I, DBF_TYPE_DATA_D,DBF_TYPE_DATA_I64, DBF_TYPE_DATA_STR, DBF_TYPE_DATA_BIN } ; + *type = t[_dt->getType(icolm)]; + *ndecimal = MAX_NDECIMALS; + //copia segura de nombre------------------ + int i =0; + char *st =_dt->getName(icolm); + for(; i<10; i++) + { + if(!st[i]) + break; + name[i]=st[i]; + } + name[i]=0; + *size = _dt->getSizeASCII(icolm); + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfGetVal(int irow, int icol, int* v ) +{ + *v = *_dt->getI(irow,icol); + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfGetVal(int irow, int icol, double* v ) +{ + *v = *_dt->getD(irow,icol); + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfGetVal(int irow, int icol, __int64* v ) +{ + *v = *_dt->getI64(irow,icol); + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfGetVal(int irow, int icol, char** v ) +{ + *v= _dt->getS(irow,icol); + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfGetVal(int irow, int icol, void** v ) +{ + *v= _dt->getBin(irow,icol); + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::DbfFinW() +{ + return true; +} +//*************************************************************************** + +bool ManagerDbfGdataTable::LeeDbf( char* path, GdataTable *db ) +{ + _dt= db; + return ManagerDbf::leer(path,this); +} +//*************************************************************************** +bool ManagerDbfGdataTable::grabaDbf( char* path, GdataTable *db ) +{ + _dt= db; + return ManagerDbf::grabar(path,this); +} +//*************************************************************************** diff --git a/ManagerDbfGdataTable.h b/ManagerDbfGdataTable.h new file mode 100644 index 0000000..020c3bb --- /dev/null +++ b/ManagerDbfGdataTable.h @@ -0,0 +1,50 @@ +#pragma once + +#ifndef ManagerDbfGdataTable_H +#define ManagerDbfGdataTable_H + +#include "base_head.h" +#include "Fdbf.h" + +class IAddColDbf +{ +public: + virtual void setData(int i, void *data)=0; +}; +class GdataTable; +class UTILES_EXPORT ManagerDbfGdataTable: public ListenerDbf_W, public ListenerDbf_R +{ + + GdataTable *_dt; + int _nrow; + int _ncolm; + public: + ManagerDbfGdataTable(void); + ~ManagerDbfGdataTable(void); + + bool LeeDbf(char* path, GdataTable *dt); + bool grabaDbf(char* path, GdataTable *dt); + bool AddCol( char* path, char* name, BYTE type,IAddColDbf *dt, int size=0); + + //funciones de herencia---------------------------------------- + //LisenerDbf_R------------------------------------------------- + virtual bool DbfSet( int nrow, int ncolm ); + virtual bool DbfSetColm( char* name, BYTE type, int size ); + virtual bool DbfaddVal( int icol, int v ); + virtual bool DbfaddVal( int icol, double v ); + virtual bool DbfaddVal( int icol, __int64 v ); + virtual bool DbfaddVal( int icol, char* v ); + virtual bool DbfaddVal( int icol, void* v ); + virtual bool DbfFinRow(); + virtual bool DbfFinR(); + //LisenerDbf_W---------------------------------------------------- + virtual bool DbfGet( int *nrow, int *ncolm ); + virtual bool DbfGetColm(int icol, char* name, BYTE *type, int *size, int*ndecimal ); + virtual bool DbfGetVal(int irow, int icol, int* v ); + virtual bool DbfGetVal(int irow, int icol, double* v ); + virtual bool DbfGetVal(int irow, int icol, __int64* v ); + virtual bool DbfGetVal(int irow, int icol, char** v ); + virtual bool DbfGetVal(int irow, int icol, void** v ); + virtual bool DbfFinW(); +}; +#endif \ No newline at end of file diff --git a/Matrix2d.h b/Matrix2d.h new file mode 100644 index 0000000..126a5b3 --- /dev/null +++ b/Matrix2d.h @@ -0,0 +1,104 @@ + +#pragma once + +#ifndef Matrix2d_h +#define Matrix2d_H + +#include "b_file.h" +#include "garray.h" +//matiz de clases genericas de 2 dimensiones +template +class ComClasFunction +{ +public: + virtual Tc comp(Tc a, Tc b) = 0; +}; +template +class Matrix2d +{ + Cgarray dat; + int ysize; +public: + Matrix2d() + { + ysize = 0; + } + bool inline inicia(int xmax, int ymax) + { + ysize = ymax; + dat.borra(); + if(!(dat+=xmax*ymax)) + return false; + dat.n = xmax*ymax; + return true; + } + + inline ClasVal* operator[](int x)//devuelve puntero a fila x + { + return dat.get(x*ysize); + } + + //******************************************************************************************************* + + inline bool graba( char* path ) + { + Cb_file file; + if(!file.abre(path,2,TRUE)) + return false; + if(!file.escribe(&ysize, sizeof(ysize))) + return false; + if(!dat.graba(&file)) + return false; + return true; + } + inline bool lee( char* path ) + { + Cb_file file; + if(!file.abre(path,1,FALSE,TRUE)) + return false; + if(!file.lee(&ysize, sizeof(ysize))) + return false; + if(!dat.leer(&file)) + return false; + return true; + } + inline void clear() + { + dat.borra(); + } + inline bool fileMix( char* path, ComClasFunction *ccomp ) + { + if(ysize<=0) + return false; + Cgarray fdat; + int yfile, xfile; + Cb_file file; + if(!file.abre(path,1,FALSE,TRUE)) + return false; + //lee tamaño matriz + if(!file.lee(&yfile, sizeof(yfile))) + return false; + if(!file.lee(&xfile, sizeof(xfile))) + return false; + xfile = xfile/yfile; + //inicia buffer + if(!(fdat+=yfile)) + return false; + //calcula numero de bytes a leer y margenes de matriz + int nb = sizeof(ClasVal)*yfile; + xfile = min(xfile, dat.n/ysize); + yfile = min(yfile, ysize); + for(int x = 0 ; xcomp(dat.get(x*ysize)[y], fdat[y]); + } + + return true; + } +}; +#endif \ No newline at end of file diff --git a/ReadMe.txt b/ReadMe.txt new file mode 100644 index 0000000..a9c487b --- /dev/null +++ b/ReadMe.txt @@ -0,0 +1,60 @@ +======================================================================== + MICROSOFT FOUNDATION CLASS LIBRARY : utiles Project Overview +======================================================================== + + +AppWizard has created this utiles DLL for you. This DLL not only +demonstrates the basics of using the Microsoft Foundation classes but +is also a starting point for writing your DLL. + +This file contains a summary of what you will find in each of the files that +make up your utiles DLL. + +utiles.vcproj + This is the main project file for VC++ projects generated using an Application Wizard. + It contains information about the version of Visual C++ that generated the file, and + information about the platforms, configurations, and project features selected with the + Application Wizard. + +utiles.h + This is the main header file for the DLL. It declares the + CutilesApp class. + +utiles.cpp + This is the main DLL source file. It contains the class CutilesApp. + +utiles.rc + This is a listing of all of the Microsoft Windows resources that the + program uses. It includes the icons, bitmaps, and cursors that are stored + in the RES subdirectory. This file can be directly edited in Microsoft + Visual C++. + +res\utiles.rc2 + This file contains resources that are not edited by Microsoft + Visual C++. You should place all resources not editable by + the resource editor in this file. + +utiles.def + This file contains information about the DLL that must be + provided to run with Microsoft Windows. It defines parameters + such as the name and description of the DLL. It also exports + functions from the DLL. + +///////////////////////////////////////////////////////////////////////////// +Other standard files: + +StdAfx.h, StdAfx.cpp + These files are used to build a precompiled header (PCH) file + named utiles.pch and a precompiled types file named StdAfx.obj. + +Resource.h + This is the standard header file, which defines new resource IDs. + Microsoft Visual C++ reads and updates this file. + +///////////////////////////////////////////////////////////////////////////// +Other notes: + +AppWizard uses "TODO:" to indicate parts of the source code you +should add to or customize. + +///////////////////////////////////////////////////////////////////////////// diff --git a/StrArray.cpp b/StrArray.cpp new file mode 100644 index 0000000..bf8e5ff --- /dev/null +++ b/StrArray.cpp @@ -0,0 +1,167 @@ +#include "StdAfx.h" +#include "StrArray.h" +//************************************************************************** +StrArray::StrArray(void) +{ + m_str=m_i=n_i=n_str=0; + str=NULL; + ind=NULL; + incremento_char=4056; + incremento_str=30; +} +//************************************************************************** +StrArray::~StrArray(void) +{ + borra(); +} +//************************************************************************** +void StrArray::cuida_memoria( int n,int ni ) +{ + //miramos si entra str mas + if (n_i+ni>=m_i) + { + if (ni>incremento_str) + m_i+=ni; + else + m_i+=incremento_str; + + if (ind) + { + ind=(int (*)[])realloc(ind,sizeof(int)*m_i); + } + else + { + ind=(int (*)[])malloc(sizeof(int)*m_i); + } + } + if (n_str+n>=m_str) + { + if (n>incremento_char) + m_str+=n; + else + m_str+=incremento_char; + if (str) + { + str=(char*)realloc(str,m_str); + } + else + { + str=(char*)malloc(m_str); + } + } +} +//************************************************************************** +void StrArray::borra() +{ + m_str=m_i=n_i=n_str=0; + if (str) + free(str); + str=NULL; + if(ind) + free(ind); + ind=NULL; +} +//************************************************************************** +char* StrArray::get( int i ) +{ + if (i<0 || i>=n_i) + return NULL; + return &str[(*ind)[i]]; +} +//************************************************************************** +int StrArray::size() +{ + return n_i; +} +//************************************************************************** +void StrArray::add( char*c ) +{ + int n=(int)strlen(c)+1; + cuida_memoria(n); + (*ind)[n_i]=n_str; + n_i++; + strcpy(&str[n_str],c); + n_str+=n; +} +//************************************************************************** +void StrArray::add( StrArray* st ) +{ + //pedimos memoria---------------------- + cuida_memoria(st->n_str,st->n_i); + //copiamos chars----------------------- + memcmp(&str[n_str], str,st->n_str); + //ponemos indices---------------------- + for (int i=0; in_i; i++) + { + (*ind)[n_i+i]=n_str+(*st->ind)[i]; + } + //monemos posiciones como llenas------- + n_i=st->n_i; + n_str+=st->n_str; +} + +void StrArray::add( char*c, int ncharReser ) +{ + char ss[1]; + ss[0]=0; + if(!c) + c = ss; + int n=max((int)strlen(c)+1, ncharReser); + cuida_memoria(n); + (*ind)[n_i]=n_str; + n_i++; + strcpy(&str[n_str],c); + n_str+=n; +} + +//************************************************************************** +void StrArray::compacta() +{ + int i=0; + for (int j=0; j=n_i) + return; + if ((i+1)add(st); + } + return buf; +} +//************************************************************************** diff --git a/StrArray.h b/StrArray.h new file mode 100644 index 0000000..df3a0d6 --- /dev/null +++ b/StrArray.h @@ -0,0 +1,36 @@ +#pragma once +#ifndef StrArray_h +#define StrArray_H + +#include "base_head.h" +class UTILES_EXPORT StrArray +{ + //variables------------------------------ + int incremento_char; + int incremento_str; +public: + char *str; + int n_str;//numero de chars + int m_str;//memoria reser + int (*ind)[]; + int n_i;//numero de str + int m_i;//memoria reser + //constructor---------------------------- +public: + StrArray(void); + ~StrArray(void); + //funciones------------------------------ + char* get(int i);//da string i + void add(char*c);//mete str + void add(char*c, int ncharReser);//mete str y reserva en memoria un minimo de ncharReser; + void add( StrArray* st );//mete un array entero de caracteres + void borra(int i);//borra el elemento iesimo + int size();//da numero de str + void borra();//borra todo + void compacta();//reduce al minimo la memoria necesaria para comtener la informacion + StrArray* filtra(StrArray*buf, char *filter); + //funciones aux------------------------- +private: + void cuida_memoria(int n,int ni=1);//asegura tener memoria para un str mas +}; +#endif \ No newline at end of file diff --git a/TaskProcess.cpp b/TaskProcess.cpp new file mode 100644 index 0000000..b7896a8 --- /dev/null +++ b/TaskProcess.cpp @@ -0,0 +1,93 @@ +#include "StdAfx.h" +#include "TaskProcess.h" +#include "Csock_cl.h" +//*********************************************************************************************** +TaskProcess::TaskProcess(void) +{ + sc = NULL; +} +//*********************************************************************************************** +TaskProcess::~TaskProcess(void) +{ + desconecta(); +} +//*********************************************************************************************** +bool TaskProcess::conecta( char* url, int port ) +{ + sc= new Csock_cl(NULL); + if(!sc->Create()) + { + return FALSE; + } + //conectamos------------------------------------------ + if (!sc->conectar(url, port)) + { + return FALSE; + } + + return true; +} +//*********************************************************************************************** +void TaskProcess::desconecta() +{ + if (sc) + { + sc->Close(); + delete sc; + sc=NULL; + } + +} +//*********************************************************************************************** +bool TaskProcess::initTask( char* ip, int port, __int64 timer ) +{ + pirate = false; + if(!conecta(ip, port)) + return false; + preTask(); + if(!pirate) + lanza(); + __int64 t1=_time64(NULL); + __int64 t2; + while(!pirate && isRunning()) + { + t2 = _time64(NULL); + if((t2-t1)>=timer) + { + inTask(); + t1 = t2; + } + Sleep(min(100, (int)size_t(timer/10))); + } + join(); + postTask(); + desconecta(); + return true; +} +//*********************************************************************************************** +bool TaskProcess::envia( void * buf, int nb ) +{ + if (sc) + return sc->envia_package((BYTE*)buf,nb)==TRUE; + return false; +} +//*********************************************************************************************** +void* TaskProcess::recibe(int *nb ) +{ + *nb = 0; + if (!sc) + return NULL; + if(!sc->recibe_package(0)) + return NULL; + *nb =sc->nb; + + return (void*)sc->buf; +} +//*********************************************************************************************** +void TaskProcess::cancela() +{ + pirate = true; + desconecta(); +} + +//*********************************************************************************************** \ No newline at end of file diff --git a/TaskProcess.h b/TaskProcess.h new file mode 100644 index 0000000..3009a32 --- /dev/null +++ b/TaskProcess.h @@ -0,0 +1,32 @@ +#pragma once +#include +#include "th.h" +#ifndef TaskProcess_h +#define TaskProcess_h +/* +Tarea delegada en otro proceso(normalmente en programa de consola) +definir en funcion override run la tarea +*/ +class Csock_cl; +class UTILES_EXPORT TaskProcess: public Cth +{ + Csock_cl *sc; +public: + bool pirate;//indica que hay que irse + + TaskProcess(void); + ~TaskProcess(void); + bool initTask(char* url, int port, __int64 timer); + bool envia(void * buf, int nb);//envia buffer al proceso principal + void* recibe(int *nb );//recibe del proceso principal nb da el numero de bytes recib + //overrides---------------------------------- + void cancela();//cancela tarea; + virtual void preTask()=0; + virtual void inTask()=0; + virtual void postTask()=0; + + virtual bool conecta(char* url, int port); + virtual void desconecta(); + +}; +#endif \ No newline at end of file diff --git a/_app.cpp b/_app.cpp new file mode 100644 index 0000000..e31dec0 --- /dev/null +++ b/_app.cpp @@ -0,0 +1,100 @@ +#include "StdAfx.h" +#include "_app.h" + +C_app *C_app::p_app=NULL; +//**************************************************** +C_app::C_app(void) +{ + pirate=FALSE; + nth=0; + C_app::p_app=this; + +} +//**************************************************** +C_app::~C_app(void) +{ +} +//**************************************************** +BOOL C_app::inicio() +{ + archi.rellena_dirs_ejecucion(); + if (!on_inicia()) + { + CWnd *Msg = new CWnd; + Msg->MessageBox(er.msg,er.modulo); + if (log.path[0]) + { + log.loguea(&er); + } + delete Msg; + return FALSE; + } + return TRUE; +} +// **************************************************** +int C_app::fin() +{ + pirate=true; + if (!on_cierra()) + { + CWnd *Msg = new CWnd; + Msg->MessageBox(er.msg,er.modulo); + delete Msg; + return FALSE; + } + while (nth>0) + Sleep(50); + return TRUE; +} +//**************************************************** +void C_app::cierra() +{ + //this->PostMessage(WM_CLOSE,0,0); + delete this; +} +//**************************************************** +BOOL C_app::on_inicia() +{ + + return TRUE; +} +//**************************************************** +BOOL C_app::on_cierra() +{ + return TRUE; +} +//**************************************************** +void C_app::suma_th() +{ + long aux; + do + { + aux=nth; + if(aux==InterlockedExchange(&nth,aux+1)) + break; + Sleep(1); + } while (TRUE); + +} + +//**************************************************** +void C_app::resta_th() +{ + long aux; + do + { + aux=nth; + if(aux==InterlockedExchange(&nth,aux-1)) + break; + Sleep(1); + } while (TRUE); +} +//**************************************************** +C_app* C_app::GetApp() +{ + if(!C_app::p_app) + C_app::p_app = new C_app(); + return C_app::p_app; +} + +//**************************************************** \ No newline at end of file diff --git a/_app.h b/_app.h new file mode 100644 index 0000000..76cfdcb --- /dev/null +++ b/_app.h @@ -0,0 +1,36 @@ +#pragma once +#include "base_head.h" +#include +#include "_error.h" +#include "dir_manager.h" +#include "_log.h" + +class UTILES_EXPORT C_app //clase aplicacion---- +{ + static C_app *p_app;//puntero a la clase aplicacion + +public: + //variables globales----------------------- + Cdir_manager archi;//manager de archivos + C_log log;//clase de trazas (log) + C_error er;//clase de manejo de errores; + //variables de thread; + BOOL pirate;//indica a los thread que hay que irse + long nth;//indica el numero de thread que hay activos + C_app(void); + virtual ~C_app(void); + //funciones y overrides------------ + static C_app* GetApp(); + BOOL inicio(); + int fin(); + void suma_th();//añade al conteo de thread +1 + void resta_th();//disminulle el conteo de thread en 1 + virtual BOOL on_inicia();//funcion inicia lo necesario para el programa + virtual BOOL on_cierra();//funcion que se ejecuta al final del todo antes de cerrar + + virtual void cierra();//fuerza el fin de la aplicacion; +protected: + +}; + + diff --git a/_error.cpp b/_error.cpp new file mode 100644 index 0000000..8af8672 --- /dev/null +++ b/_error.cpp @@ -0,0 +1,58 @@ +#include "StdAfx.h" +#include "_error.h" +//*********************************************************** + +C_error::C_error(void) +{ + limpia(); +} +//*********************************************************** +C_error::~C_error(void) +{ +} +//*********************************************************** +void C_error::pon_win( char *modulo ) +{ + DWORD dw; + + strcpy(this->modulo,modulo); + dw = GetLastError(); + + if(dw==NO_ERROR) + { + tipo=NO_ERROR; + return; + } + FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + dw, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &msg, + 256, + NULL ); + tipo=(int)dw; +} +//*********************************************************** +void C_error::pon( char *mod, char *mens, int tip/*=-1*/ ) +{ + strcpy(this->modulo,mod); + tipo=tipo; + strcpy(msg,mens); +} +//*********************************************************** +void C_error::aclara( char *mens ) +{ + char str[256]; + sprintf(str,"%s: %s",mens,msg); + strcpy(msg,str); +} +//*********************************************************** +void C_error::limpia() +{ + tipo=NO_ERROR; + msg[0]=0; + modulo[0]=0; +} +//*********************************************************** diff --git a/_error.h b/_error.h new file mode 100644 index 0000000..addbae9 --- /dev/null +++ b/_error.h @@ -0,0 +1,19 @@ +#pragma once +#include "base_head.h" + +class UTILES_EXPORT C_error +{ +public: + //variables----------------------------- + char modulo[32];//parte del programa que causa el error + char msg[256];//mensaje de error + int tipo;//codigo de error + //constructor--------------------------- + C_error(void); + virtual ~C_error(void); + //funciones----------------------------- + void pon(char *mod, char *mens, int tip=-1);//pone error propio + void pon_win(char *modulo);//pone error windows + void aclara(char *mens);//pone aclaracion + void limpia();//limpia error +}; diff --git a/_log.cpp b/_log.cpp new file mode 100644 index 0000000..8079232 --- /dev/null +++ b/_log.cpp @@ -0,0 +1,145 @@ +#include "StdAfx.h" +#include "_log.h" +#include "_error.h" +#include "_app.h" +//*********************************************************************** +C_log::C_log(void) +{ + nombre[0]=0; + path[0]=0; + archivo_log=-1; + + log_ext=NULL; + l_lisener=NULL; +} +//*********************************************************************** +C_log::~C_log(void) +{ +} +//*********************************************************************** + +void C_log::loguea(__time64_t tiemp, char *modulo, char *fmt) +{ + char nfile[256], str[2048]; + int k; + char mod[31]; + CTime tiempo; + OFSTRUCT sarchivo; + CString texto; + char tiem[20]; + + if (log_ext) + log_ext(tiemp,modulo,fmt); + if (l_lisener) + l_lisener->log_ext(tiemp,modulo,fmt); + if (!nombre[0]) + return; + + cerrojo.entro(); + //****************************** + //TODO + /*va_start(arg_ptr, fmt); + _vsnprintf(buf,4090, fmt, arg_ptr); + va_end(arg_ptr);*/ + + texto = fmt; + tiempo = CTime::GetCurrentTime(); + // Actualizar el fichero de LOG + //EnterCriticalSection(&sincro); + if (archivo_log < 0) + { + // Abrir fichero de LOG + nb=0; + if(path[0]) + sprintf (nfile, "%s\\%s_%04ld_%02ld_%02ld_h%02ld.log", path,nombre, + tiempo.GetYear(),tiempo.GetMonth(),tiempo.GetDay(),tiempo.GetHour()); + else + sprintf (nfile, "%s_%04ld_%02ld_%02ld_h%02ld.log", nombre, + tiempo.GetYear(),tiempo.GetMonth(),tiempo.GetDay(),tiempo.GetHour()); + archivo_log = OpenFile( nfile, &sarchivo, OF_EXIST); + if ( archivo_log != -1) + { + archivo_log = OpenFile( nfile, &sarchivo, OF_WRITE); + SetFilePointer((HANDLE) (__int64) archivo_log,0,0,FILE_END); + } + else + { + archivo_log = OpenFile( nfile, &sarchivo, OF_CREATE); + } + } + if (archivo_log >= 0) + { + k = (int) strlen(texto); + int max = 2048 - 128; + if (k > (2048 - 128)) + texto.SetAt(2048 - 128,0); + + int st=(int)strlen(modulo); + for (int i=0; i<30; i++) + { + if (i52428800)//mallor de 50 megas + { + strcpy(str,"Cierre de archivo, se creara uno nuevo para logear\r\n"); + _lwrite(archivo_log,str,(int)strlen(str)); + k = GetFileSize ((HANDLE) (__int64) archivo_log, NULL); + if (k > 200) + { + _lclose(archivo_log); + archivo_log = -1; + } + } + } + else + path[0]=0; + cerrojo.salgo(); +} +//*********************************************************************** +void C_log::loguea( char *modulo, char *fmt ) +{ + loguea(_time64(NULL),modulo,fmt); +} +//*********************************************************************** +void C_log::loguea( C_error *er ) +{ + loguea(_time64(NULL),er->modulo,er->msg); +} +//*********************************************************************** +void C_log::log( char *modulo, char *fmt,... ) +{ + if (C_app::GetApp()) + { + char buf[1024]; + int k; + va_list arg_ptr; + va_start(arg_ptr, fmt); + k = _vsnprintf(buf, 1020, fmt, arg_ptr); + va_end(arg_ptr); + if (k<0) + strcpy(&buf[1020], "..."); + C_app::GetApp()->log.loguea(modulo, buf); + } +} +//*********************************************************************** +void C_log::log( C_error *er ) +{ + if (C_app::GetApp()) + { + C_app::GetApp()->log.loguea(_time64(NULL),er->modulo,er->msg); + } +} +//*********************************************************************** diff --git a/_log.h b/_log.h new file mode 100644 index 0000000..0f56f96 --- /dev/null +++ b/_log.h @@ -0,0 +1,42 @@ +#pragma once +#include "base_head.h" +#include "lock.h" +#include +typedef struct Msg_evento_log +{ + int id_e; + char nivel[64]; + char mensage[256]; + __time64_t tiempo; +}Msg_evento_log; +class C_error; +class UTILES_EXPORT C_escucha_log//clase para escuchar eventos de log +{ +public: + virtual void log_ext(__time64_t tiemp, char *modulo, char *fmt)=0; +}; +class UTILES_EXPORT C_log//clase para logear eventos +{ +public: + //variavles----------------------------------------- + HFILE archivo_log; + int nb; + Clock cerrojo; + C_escucha_log *l_lisener;//puntero a escucha actual + //BOOL log_consola; + char nombre[32]; + char path[256]; + + void (*log_ext)(__time64_t tiemp, char *modulo, char *fmt);//funcion de log externa + C_log(void); + ~C_log(void); + //funcion------------------------------------------- + void loguea(__time64_t tiemp, char *modulo, char *fmt);//añade un suceso + void loguea(char *modulo, char *fmt);//añade suceso actual + void loguea(C_error *er);//añade el error como suceso + static void log(char *modulo, char *fmt,...);//funcion estatica para loguear + static void log( C_error *er ); + //static void log(std::string &mod, std::string &msg); + +}; + diff --git a/_proceso.cpp b/_proceso.cpp new file mode 100644 index 0000000..18739ee --- /dev/null +++ b/_proceso.cpp @@ -0,0 +1,67 @@ +#include "StdAfx.h" +#include "_proceso.h" + +C_proceso::C_proceso(void) +{ + strcpy(nombre, "Proceso sin nombre"); + m_thread=NULL; +} + +C_proceso::~C_proceso(void) +{ + join(); +} +//********************************************************************************************** +void C_proceso::run() +{ + +} +//********************************************************************************************** +BOOL C_proceso::lanza( char *nombre/*=NULL*/ ) +{ + if (nombre) + strcpy(this->nombre,nombre); + m_thread = AfxBeginThread(main_c_proceso, this, THREAD_PRIORITY_NORMAL, 1024, CREATE_SUSPENDED); + m_thread->m_bAutoDelete=FALSE; +#ifdef _DEBUG + SetThreadName(m_thread->m_nThreadID,this->nombre); +#endif + m_thread->ResumeThread(); + return TRUE; +} +//********************************************************************************************** +void C_proceso::join() +{ + if (m_thread == NULL) + return; + WaitForSingleObject(m_thread->m_hThread,INFINITE); + delete m_thread; + m_thread = NULL; +} + +//********************************************************************************************** +UINT main_c_proceso( LPVOID pp ) +{ + C_proceso *p=(C_proceso*)pp; + p->run(); + AfxEndThread(0,FALSE); + return 0; +} +//********************************************************************************************** +UTILES_EXPORT void SetThreadName( DWORD dwThreadID, char* threadName) +{ + THREADNAME_INFO info; + info.dwType = 0x1000; + info.szName = threadName; + info.dwThreadID = dwThreadID; + info.dwFlags = 0; + + __try + { + RaiseException( MS_VC_EXCEPTION_PROCESO_UTILES, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info ); + } + __except(EXCEPTION_EXECUTE_HANDLER) + { + } +}; +//********************************************************************************************** diff --git a/_proceso.h b/_proceso.h new file mode 100644 index 0000000..9451101 --- /dev/null +++ b/_proceso.h @@ -0,0 +1,28 @@ +#pragma once +#include "base_head.h" + +const DWORD MS_VC_EXCEPTION_PROCESO_UTILES=0x406D1388; + +#pragma pack(push,8) +typedef struct tagTHREADNAME_INFO +{ + DWORD dwType; // Must be 0x1000. + LPCSTR szName; // Pointer to name (in user addr space). + DWORD dwThreadID; // Thread ID (-1=caller thread). + DWORD dwFlags; // Reserved for future use, must be zero. +} THREADNAME_INFO; +#pragma pack(pop) + +class UTILES_EXPORT C_proceso//proceso base +{ +public: + C_proceso(void); + char nombre[32]; + CWinThread * m_thread; + virtual ~C_proceso(void); + BOOL lanza(char *nombre=NULL);//lanzar thread + virtual void run();//funcion que hace el thread + void join();//espera al thread +}; +UINT main_c_proceso(LPVOID pp); +UTILES_EXPORT void SetThreadName( DWORD dwThreadID, char* threadName); \ No newline at end of file diff --git a/_zip.cpp b/_zip.cpp new file mode 100644 index 0000000..cc55dee --- /dev/null +++ b/_zip.cpp @@ -0,0 +1,797 @@ +#include "stdafx.h" +#include "_zip.h" +#include "igt_error.h" +#include +#include +#include +//***************************************************************************************************** +Cigt_zip::Cigt_zip(void) +{ + nivel_compresion=6; + uf=NULL; + zf=NULL; + igt_err=new Cigt_error(); + borrar_error=TRUE; + nombre_zip[0]='\0'; +} +//***************************************************************************************************** +Cigt_zip::Cigt_zip(Cigt_error *err) +{ + nombre_zip[0]='\0'; + nivel_compresion=6; + uf=NULL; + zf=NULL; + borrar_error=FALSE; + igt_err=err; +} +//***************************************************************************************************** +Cigt_zip::~Cigt_zip(void) +{ + cierra_zip(); + if (borrar_error&&igt_err) + { + delete igt_err; + } + igt_err=NULL; + +} +//***************************************************************************************************** +int Cigt_zip::isLargeFile(char* filename ) +{ + int largeFile = 0; + ZPOS64_T pos = 0; + FILE* pFile = fopen64(filename, "rb"); + + if(pFile != NULL) + { + int n = fseeko64(pFile, 0, SEEK_END); + + pos = ftello64(pFile); + if(pos >= 0xffffffff) + largeFile = 1; + + fclose(pFile); + } + + return largeFile; +} +//************************************************************************************************************** +BOOL Cigt_zip::abre_zip( char *filename, int parametro ) +{ + int esc; + zlib_filefunc64_def ffunc; + fill_win32_filefunc64A(&ffunc); + if (parametro==READ) + { + cierra_zip_uf(); + uf = new unzFile(); + *uf = unzOpen2_64(filename,&ffunc); + if (uf==NULL) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + return FALSE; + } + strcpy(nombre_zip,filename); + return TRUE; + } + if (parametro==OWERWRITE) + { + esc=0; + } + else + esc=2; + cierra_zip_zf(); + zf= new zipFile(); + *zf = zipOpen2_64(filename,esc,NULL,&ffunc);// + if (zf == NULL)// + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + return FALSE; + } + strcpy(nombre_zip,filename); + return TRUE; +} +//***************************************************************************** +BOOL Cigt_zip::addfile(char *newfile, char *dir_in_zip ) +{ + FILE *fin; + int err=0,size_read=0; + int zip64=0; + zip_fileinfo zi; + unsigned long crcFile=0; + char *password=NULL; + int size_buf = WRITEBUFFERSIZE; + if (!zf) + { + igt_err->pon_error("Cigt_zip","puntero del handle nulo",-1); + Cigt_error::pon_winerror("Cigt_zip",igt_err); + return FALSE; + } + void *buf = (void*)malloc(size_buf); + + zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = + zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; + zi.dosDate = 0; + zi.internal_fa = 0; + zi.external_fa = 0; + filetime(newfile,&zi.tmz_date,(long*)&zi.dosDate); + err = getFileCrc(newfile,buf,size_buf,&crcFile);//preparamos crc + zip64 = isLargeFile(newfile); + err = zipOpenNewFileInZip3_64(*zf,dir_in_zip,&zi, + NULL,0,NULL,0,NULL /* comment*/, + 8,nivel_compresion,0, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + password,crcFile, zip64);//preparamos el zip + if (err != ZIP_OK) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + } + else + { + fin = fopen64(newfile,"rb");//abre el archivo a meter en zip + if (fin==NULL) + { + err=ZIP_ERRNO; + //printf("error in opening %s for reading\n",newfile); + } + } + if (err == ZIP_OK) + { + do// bucle para escribir el archivo en zip + { + err = ZIP_OK; + size_read = (int)fread(buf,1,size_buf,fin);//leemos parte + if (size_read < size_buf) + if (feof(fin)==0) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + err = ZIP_ERRNO; + } + + if (size_read>0) + { + err = zipWriteInFileInZip (*zf,buf,size_read); + if (err<0) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + err = ZIP_ERRNO; + } + } + } while ((err == ZIP_OK) && (size_read>0)); + } + if (fin) + fclose(fin);//cierra el archivo metido + if (buf) + { + free(buf); + } + if (err<0)//si errores + return FALSE; + return TRUE; +} +//***************************************************************************************************** +BOOL Cigt_zip::cierra_zip_zf() +{ + int errclose= ZIP_OK; + if(zf) + { + errclose = zipClose(*zf,NULL); + if (errclose != ZIP_OK) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + return FALSE; + } + zf=NULL; + } + return TRUE; + +} +//***************************************************************************************************** +/* calculate the CRC32 of a file, + because to encrypt a file, we need known the CRC32 of the file before */ +int Cigt_zip::getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc) +{ + unsigned long calculate_crc=0; + int err=ZIP_OK; + FILE * fin = fopen64(filenameinzip,"rb"); + unsigned long size_read = 0; + unsigned long total_read = 0; + if (fin==NULL) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + err = ZIP_ERRNO; + } + + if (err == ZIP_OK) + do + { + err = ZIP_OK; + size_read = (int)fread(buf,1,size_buf,fin); + if (size_read < size_buf) + if (feof(fin)==0) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + err = ZIP_ERRNO; + } + + if (size_read>0) + calculate_crc = crc32(calculate_crc,(Bytef*)buf,size_read); + total_read += size_read; + + } while ((err == ZIP_OK) && (size_read>0)); + + if (fin) + fclose(fin); + + *result_crc=calculate_crc; + //printf("file %s crc %lx\n", filenameinzip, calculate_crc); + return err; +} +//***************************************************************************************************** +int Cigt_zip::filetime( char *f, tm_zip *tmzip, long *dt_ ) +{ + uLong *dt=(uLong *)dt_; + int ret = 0; + { + FILETIME ftLocal; + HANDLE hFind; + WIN32_FIND_DATAA ff32; + hFind = FindFirstFileA(f,&ff32); + if (hFind != INVALID_HANDLE_VALUE) + { + FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal); + FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0); + FindClose(hFind); + ret = 1; + } + } + return ret; +} +//***************************************************************************************************** +BOOL Cigt_zip::cierra_zip() +{ + BOOL resul; + resul=cierra_zip_uf(); + return cierra_zip_zf() && resul; +} + +//***************************************************************************************************** +BOOL Cigt_zip::descomprimir(char *file, char *fileout,BYTE **bufex,int *nb ) +{ + FILE *fout=NULL; + int err = UNZ_OK; + int mb; + BYTE (*bufsal)[]; + bufsal=NULL; + int size_buf=0; + const char* password=NULL; + //zlib_filefunc64_def ffunc; + void *buf; + unz_file_info64 file_info; + char path_inzip[256]; + if (!uf) + { + igt_err->pon_error("Cigt_zip","Error al descomprimir: puntero del handle uf nulo",-1); + return FALSE; + } + //int ret_value = do_extract_onefile(uf, file, 0, 0, "\0"); + if (unzLocateFile(uf,file,CASESENSITIVITY)!=UNZ_OK)//comprueba que esta el archivo en el zip + { + char str[250]; + sprintf(str,"Cigt_zip","Error al descomprimir: el archivo %s no se encuentra en el zip",file); + igt_err->pon_error("Cigt_zip",str,-1); + return FALSE; + } + + + err = unzGetCurrentFileInfo64(uf,&file_info,path_inzip,sizeof(path_inzip),NULL,0,NULL,0); + if (err!=UNZ_OK) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + return FALSE; + } + + size_buf = WRITEBUFFERSIZE; + buf = (void*)malloc(size_buf); + if (buf==NULL) + { + char str[256]; + sprintf(str,"Cigt_zip","Error al descomprimir: no se puede reservar memoria para buf de %ld bytes",size_buf); + igt_err->pon_error("Cigt_zip",str,-1); + return FALSE; + } + err = unzOpenCurrentFilePassword(uf,password); + if (err!=UNZ_OK) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + return FALSE; + } + if (fileout) + fout=fopen64(fileout,"wb"); + else + { + *nb=0; + mb=WRITEBUFFERSIZE*5; + bufsal = (BYTE (*)[])malloc(mb); + } + /* some zipfile don't contain directory alone before file */ + if (fout!=NULL||!fileout) + { + do//bucle para escribir archivo + { + err = unzReadCurrentFile(uf,buf,size_buf); + if (err<0) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + break; + } + if (err>0) + if(fileout) + { + if (fwrite(buf,err,1,fout)!=1) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + err=UNZ_ERRNO; + break; + } + } + else + { + if ((*nb+err)>=mb) + { + mb+=WRITEBUFFERSIZE*5; + bufsal=(BYTE(*)[])realloc(bufsal,mb); + } + memcpy(&(*bufsal)[*nb],buf,err); + *nb+=err; + } + } + while (err>0); + } + if (fout) + fclose(fout); + free(buf); + if (err==UNZ_OK) + { + if (fileout) + { + change_file_date(fileout,file_info.dosDate, + file_info.tmu_date); + } + else + { + *bufex=(BYTE*)bufsal; + } + return TRUE; + } + if (bufsal) + { + free(bufsal); + } + return FALSE; +} +//***************************************************************************************************** +BOOL Cigt_zip::descomprimir() +{ + int n; + Zip_struct (*contenido)[]; + contenido= (Zip_struct(*)[])listar(&n); + if (n<=0) + return FALSE; + for (int i=0; i>16),(WORD)dosdate,&ftLocal); + LocalFileTimeToFileTime(&ftLocal,&ftm); + SetFileTime(hFile,&ftm,&ftLastAcc,&ftm); + CloseHandle(hFile); +} +//***************************************************************************************************** +BOOL Cigt_zip::descomprimir2file( char *file,char *fileout ) +{ + if (fileout) + return descomprimir(file,fileout,NULL,NULL); + return FALSE; +} +//***************************************************************************************************** +BOOL Cigt_zip::descomprimir2file( char *file ) +{ + char fileout[256]; + int i; + int j; + strcpy(fileout,nombre_zip); + for (i=strlen(fileout);i>=0;i--) + { + if(fileout[i]=='\\') + { + fileout[i]='\\'; + i++; + fileout[i]='\0'; + break; + } + } + if (i<0) + i=0; + for(j=0; *(file+j); j++) + { + if (*(file+j)=='\\') + { + *(fileout+j+i)='\0'; + if(!crea_dir(fileout)) + { + return FALSE; + } + } + *(fileout+j+i)=*(file+j); + } + *(fileout+j+i)='\0'; + return descomprimir2file(file,fileout); +} +//***************************************************************************************************** +BOOL Cigt_zip::descomprimir2buff(char *file,BYTE **buf,int *nb ) +{ + return descomprimir(file,NULL,buf,nb); +} +//***************************************************************************************************** +Zip_struct* Cigt_zip::listar(int* n) +{ + int err = UNZ_OK; + //zlib_filefunc64_def ffunc; + unz_file_info64 file_info; + uLong i; + unz_global_info64 gi; + //char path_inzip[256]; + *n=0; + Zip_struct (*salida)[]; + salida=NULL; + + err = unzGetGlobalInfo64(uf,&gi); + if (err!=UNZ_OK) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + } + if (gi.number_entry<=0) + { + igt_err->pon_error("Cigt_zip","Error en listar: en número de archivos del zip es <=0"); + return NULL; + } + salida=(Zip_struct(*)[])malloc(sizeof(Zip_struct)*gi.number_entry); + *n=gi.number_entry; + for (i=0;i0) + { + (*salida)[i].ratio = (int)((file_info.compressed_size*100)/file_info.uncompressed_size); + (*salida)[i].size_descom=(int)file_info.uncompressed_size; + } + else + { + (*salida)[i].ratio = 0; + (*salida)[i].size_descom=0; + } + /* display a '*' if the file is crypted */ + if ((file_info.flag & 1) != 0) + (*salida)[i].encript=TRUE; + else + (*salida)[i].encript=FALSE; + + (*salida)[i].compresion=file_info.compression_method; + (*salida)[i].size=file_info.compressed_size; + + if ((i+1)pon_error("Cigt_zip","Error al crear carpeta: carpeta no encontrada",k); + return FALSE; + } + } + return TRUE; +} +//***************************************************************************************************** +BOOL Cigt_zip::abre_zip_temp() +{ + char szTempFileName[256]; + char lpTempPathBuffer[256]; + //char chBuffer[512]; + //LPCTSTR errMsg; + DWORD dwRetVal = 0; + // Gets the temp path env string (no guarantee it's a valid path). + dwRetVal = GetTempPath(MAX_PATH, // length of the buffer + lpTempPathBuffer); // buffer for path + if (dwRetVal > MAX_PATH || (dwRetVal == 0)) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + return FALSE; + } + + // Generates a temporary file name. + dwRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files + "DEMO", // temp file name prefix + 0, // create unique name + szTempFileName); // buffer for name + if (dwRetVal == 0) + { + Cigt_error::pon_winerror("Cigt_zip",igt_err); + return FALSE; + } + return abre_zip(szTempFileName,OWERWRITE); +} +//***************************************************************************************************** +BOOL lista_file_dir( char *dir,Cstr_array *lista_file, Cigt_error *err) +{ + return lista_file_dir(dir,NULL,lista_file,err); + /* + BOOL poner_error; + char str[256]; + //int k; + WIN32_FIND_DATA filedat; + HANDLE hfile; + if (err) + poner_error=TRUE; + else + poner_error=FALSE; + if (!lista_file) + { + err->pon_error("lista_file_dir","Puntero de lista_file nulo",-1); + return FALSE; + } + + strcpy(str,dir); + if (str[strlen(str)-1] != '\\') + strcat(str,"\\"); + strcat(str,"*.*"); + hfile = FindFirstFile(str,&filedat); + + if (hfile != INVALID_HANDLE_VALUE)//existe dir + { + // existe el dir + do + { + if ((strcmp(filedat.cFileName,".") != 0) && + (strcmp(filedat.cFileName,"..") != 0)) + { + strcpy(str,dir); + if (str[strlen(str)-1] != '\\') + strcat(str,"\\"); + strcat(str,filedat.cFileName); + if (filedat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + if(!lista_file_dir( str, lista_file, err)) + { + FindClose(hfile); + return FALSE; + } + } + else + { + lista_file->pon_str(str); + } + } + } while (FindNextFile(hfile,&filedat)); + FindClose(hfile); + + } + else + { + if (poner_error) + Igt_error::pon_winerror("lista_file_dir",err); + return FALSE; + } + return TRUE; + */ +} +//***************************************************************************************************** +BOOL lista_file_dir( char *dir,char *omite,Cstr_array *lista_file,Cigt_error *err ) +{ + BOOL poner_error; + char str[256]; + //int k; + WIN32_FIND_DATA filedat; + HANDLE hfile; + if (err) + poner_error=TRUE; + else + poner_error=FALSE; + if (!lista_file) + { + err->pon_error("lista_file_dir","Puntero de lista_file nulo",-1); + return FALSE; + } + + strcpy(str,dir); + if (str[strlen(str)-1] != '\\') + strcat(str,"\\"); + strcat(str,"*.*"); + hfile = FindFirstFile(str,&filedat); + + if (hfile != INVALID_HANDLE_VALUE)//existe dir + { + // existe el dir + do + { + if ((strcmp(filedat.cFileName,".") != 0) && + (strcmp(filedat.cFileName,"..") != 0)) + { + if (!omite||strcmp(omite,filedat.cFileName)!=0) + { + strcpy(str,dir); + if (str[strlen(str)-1] != '\\') + strcat(str,"\\"); + strcat(str,filedat.cFileName); + if (filedat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + if(!lista_file_dir( str,NULL, lista_file, err)) + { + FindClose(hfile); + return FALSE; + } + } + else + { + lista_file->pon_str(str); + } + } + } + } while (FindNextFile(hfile,&filedat)); + FindClose(hfile); + + } + else + { + if (poner_error) + Cigt_error::pon_winerror("lista_file_dir",err); + return FALSE; + } + return TRUE; +} +//***************************************************************************************************** +BOOL es_dir(char *dir) +{ + WIN32_FIND_DATA filedat; + HANDLE hfile; + hfile = FindFirstFile(dir,&filedat); + if (hfile != INVALID_HANDLE_VALUE)//existe dir + { + if (filedat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + FindClose(hfile); + return TRUE; + } + FindClose(hfile); + } + return FALSE; +} +//***************************************************************************************************** +BOOL del_File(char *file,Cigt_error *err) +{ + //borra archivos y carpetas + BOOL poner_error; + char str[256]; + int n_aux; + //int k; + WIN32_FIND_DATA filedat; + HANDLE hfile; + if (err) + poner_error=TRUE; + else + poner_error=FALSE; + n_aux=strlen(file); + + if (n_aux<3) + { + if (poner_error) + { + sprintf(str,"Error al borrar archivo: %s. Borrar este archivo puede ser peligroso"); + err->pon_error("del_File",str,-1); + } + return FALSE; + } + strcpy(str,file); + if (str[strlen(str)-1] != '\\') + strcat(str,"\\"); + strcat(str,"*.*"); + hfile = FindFirstFile(str,&filedat); + if (hfile != INVALID_HANDLE_VALUE) + { + // existe el dir + // borralo y usalo + do + { + if ((strcmp(filedat.cFileName,".") != 0) && + (strcmp(filedat.cFileName,"..") != 0)) + { + strcpy(str,file); + if (str[strlen(str)-1] != '\\') + strcat(str,"\\"); + strcat(str,filedat.cFileName); + if (filedat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + if(!del_File(str,err)) + { + FindClose(hfile); + return FALSE; + } + } + else + { + SetFileAttributes(str,FILE_ATTRIBUTE_NORMAL); + if (!DeleteFile(str)) + { + Cigt_error::pon_winerror("del_File",err); + FindClose(hfile); + return FALSE; + } + } + } + } while (FindNextFile(hfile,&filedat)); + FindClose(hfile); + if (!RemoveDirectory(file)) + { + Cigt_error::pon_winerror("del_File",err); + FindClose(hfile); + return FALSE; + } + } + return TRUE; +} +//***************************************************************************************************** + + diff --git a/_zip.h b/_zip.h new file mode 100644 index 0000000..38fa55f --- /dev/null +++ b/_zip.h @@ -0,0 +1,83 @@ +#pragma once +#define USEWIN32IOAPI + +/* +#ifndef _WIN32 +#ifndef __USE_FILE_OFFSET64 +#define __USE_FILE_OFFSET64 +#endif +#ifndef __USE_LARGEFILE64 +#define __USE_LARGEFILE64 +#endif +#ifndef _LARGEFILE64_SOURCE +#define _LARGEFILE64_SOURCE +#endif +#ifndef _FILE_OFFSET_BIT +#define _FILE_OFFSET_BIT 64 +#endif +#endif +*/ +#include "zconf.h" +#include "zip.h" +#include "unzip.h" +#ifdef _WIN32 +#define USEWIN32IOAPI +#include "iowin32.h" +#endif +#define WRITEBUFFERSIZE (8192) +#define MAXFILENAME (256) +#define CASESENSITIVITY (0) + +typedef struct Zip_struct +{ + char nombre[256]; + int size; + int size_descom; + int ratio; + int compresion; + BOOL encript; +}Zip_struct; +class Cigt_error; +class C_zip +{ +public: + enum + { + READ, + WRITE, + OWERWRITE + }; + Cigt_error *igt_err; + char nombre_zip[256]; + zipFile *zf; + unzFile *uf; + Cigt_zip(void); + Cigt_zip(Cigt_error *err); + ~Cigt_zip(void); + BOOL borrar_error; + + int nivel_compresion;//nivel de compresion + BOOL abre_zip(char *filename,int parametro);//abre zip y deja el handle en zf + BOOL addfile(char *newfile,char *dir_in_zip);//introduce el archivo newfile con dir dentro del zip dir_in_zip + BOOL descomprimir2file(char *file,char *fileout);//descomprime el archivo file y lo pone en archivo fileout + BOOL descomprimir2file(char *file);//Descomprime el archivo file y lo pone en la ruta relativa del zip + BOOL descomprimir2buff(char *file,BYTE **buf,int *nb );//Descomprime el archivo file y lo carga en buf + BOOL descomprimir();//Descomprime el zip entero y lo pone en la ruta relativa del zip; + Zip_struct* listar(int* n);//devuelve una estructura con informacion del contenido del zip,sinedo n el numero de archivos en el zip + BOOL cierra_zip();//Cierra handle + BOOL abre_zip_temp();//Crea un archivo vacio en la carpeta temporal de windows (el Path del archivo se puede obtener de la variable nombre_zip) +private: + BOOL crea_dir(char *dir); + BOOL descomprimir(char *file,char *fileout,BYTE **bufex,int *n);//descomprime del archivo filezip el archivo file y lo pone en dirout o en el bufex si dirout==NULL + BOOL cierra_zip_zf();//cierra el handle escritura + BOOL cierra_zip_uf();//cierra handle lectura + //funciones auxiliares + int isLargeFile(char* filename); + int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc); + int filetime(char *f, tm_zip *tmzip, long *dt_); + void change_file_date(const char *filename,uLong dosdate,tm_unz tmu_date); +}; +BOOL lista_file_dir(char *dir,Cstr_array *lista_file,Cigt_error *err);//Lista todos los archivos que contiene la carpeta dir +BOOL lista_file_dir(char *dir,char *omite, Cstr_array *lista_file,Cigt_error *err);//Lista todos los archivos que contiene la carpeta dir omitiendo "omite" +BOOL es_dir(char *dir);//Comprueba si dir es una carpeta +BOOL del_File(char *file,Cigt_error *err);//Borra todos los archivos que contiene la carpeta dir \ No newline at end of file diff --git a/ascii_file.cpp b/ascii_file.cpp new file mode 100644 index 0000000..0a4ff2d --- /dev/null +++ b/ascii_file.cpp @@ -0,0 +1,190 @@ +#include "StdAfx.h" +#include "ascii_file.h" +#include "_error.h" +#define MODULO_ASCII_FILE "Cascii_file" +//************************************************************************************************* +Cascii_file::Cascii_file(C_error* err) +{ + if (err) + { + b_er=FALSE; + er=err; + } + else + { + er= new C_error(); + b_er=TRUE; + } +} +//************************************************************************************************* +Cascii_file::~Cascii_file(void) +{ + if(b_er && er) + { + delete er; + } +} +//************************************************************************************************* +BOOL Cascii_file::lee( char* path) +{ + char *buf=NULL; + char *s1; + char *s2; + borra(); + HANDLE hfile=INVALID_HANDLE_VALUE; + DWORD dw,nb; + //abrimos archivo--------------------- + + hfile = CreateFile(path, GENERIC_READ, 0, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + + if (hfile == INVALID_HANDLE_VALUE) + { + er->pon_win(MODULO_ASCII_FILE); + return FALSE; + } + + nb=SetFilePointer(hfile,0,NULL,FILE_END); + if(nb==INVALID_SET_FILE_POINTER) + { + er->pon_win(MODULO_ASCII_FILE); + goto salgo; + } + buf=(char *)malloc(nb+2); + + dw=SetFilePointer(hfile,0,NULL,FILE_BEGIN); + if(dw==INVALID_SET_FILE_POINTER) + { + er->pon_win(MODULO_ASCII_FILE); + goto salgo; + } + if (!ReadFile(hfile, (LPSTR) buf ,nb,&dw,NULL)) + { + er->pon_win(MODULO_ASCII_FILE); + goto salgo; + } + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + buf[nb]=0; + buf[nb+1]=0;//aseguramos el final de la cadena; + s1=buf; + //procesamos----------------------------------------------- + while (*s1) + { + s2=busca_salto_linea(s1); + if (*s2) + { + *s2=0; + s2++; + while(*s2=='\r' ||*s2=='\n') + s2=s2+1; + } + if (strlen(s1)>0) + { + lineas.add(s1); + } + s1=s2; + } + free(buf); + return TRUE; +salgo: + if (hfile!=INVALID_HANDLE_VALUE) + CloseHandle(hfile); + if (buf) + free(buf); + return FALSE; + +} +//************************************************************************************************* +BOOL Cascii_file::guarda( char* path, BOOL ret_carro ) +{ + HANDLE hfile=INVALID_HANDLE_VALUE; + DWORD dw; + char* str; + int n= lineas.size(); + char salto='\n'; + char ret='\r'; +/* + er->pon(MODULO_INI_FILE,"guarda: Función no implementada"); + return FALSE;*/ + //abrimos archivo------------------------------- + hfile=CreateFile(path, + GENERIC_WRITE, + 0, // exclusive access + NULL, // no security + CREATE_ALWAYS, + 0, // no overlapped I/O + NULL); // null template + + if (hfile == INVALID_HANDLE_VALUE) + { + er->pon_win(MODULO_ASCII_FILE); + return FALSE; + } + //guardamos--------------------------------- + for (int i=0; ipon_win(MODULO_ASCII_FILE); + goto salgo; + } + if (ret_carro) + { + if(!WriteFile(hfile, &ret, 1, &dw, NULL)) + { + er->pon_win(MODULO_ASCII_FILE); + goto salgo; + } + } + if(!WriteFile(hfile, &salto, 1, &dw, NULL)) + { + er->pon_win(MODULO_ASCII_FILE); + goto salgo; + } + } + } + //cerramos---------------------------------- + if(hfile!=INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + } + return TRUE; + +salgo: + if(hfile!=INVALID_HANDLE_VALUE) + CloseHandle(hfile); + return FALSE; +} +//************************************************************************************************* +int Cascii_file::get() +{ + return lineas.size(); +} +//************************************************************************************************* +char* Cascii_file::get( int i ) +{ + return lineas.get(i); +} +//************************************************************************************************* +void Cascii_file::borra() +{ + lineas.borra(); +} +//************************************************************************************************* +void Cascii_file::add( char* l ) +{ + lineas.add(l); +} +//************************************************************************************************* +char* Cascii_file::busca_salto_linea( char* st ) +{ + char *s=st; + while(*s && *s!='\r' && *s!='\n' ) + s=s+1; + return s; +} +//************************************************************************************************* diff --git a/ascii_file.h b/ascii_file.h new file mode 100644 index 0000000..dd2ac30 --- /dev/null +++ b/ascii_file.h @@ -0,0 +1,27 @@ +#pragma once +#include "base_head.h" +#include "StrArray.h" +class C_error; +class UTILES_EXPORT Cascii_file +{ + //variables------------------------------------------------ +private: + StrArray lineas; + C_error *er; + BOOL b_er; +public: + Cascii_file(C_error* err=NULL); + ~Cascii_file(void); + + //funciones------------------------------------------------ + + BOOL lee(char* path);//lee un archivo + BOOL guarda(char* path,BOOL ret_carro=TRUE);//guarda un archivo + int get();//dice el numero de lineas + char* get(int i);//da la linea i-esima + void borra();//borra todo + void add(char* l);//añade linea + +private: + char* busca_salto_linea(char*st); +}; diff --git a/b_file.cpp b/b_file.cpp new file mode 100644 index 0000000..a412269 --- /dev/null +++ b/b_file.cpp @@ -0,0 +1,66 @@ +#include "StdAfx.h" +#include "b_file.h" +//****************************************************************************************************************** +Cb_file::Cb_file(void) +{ + hfile=INVALID_HANDLE_VALUE; + er=NULL; +} +//****************************************************************************************************************** +Cb_file::~Cb_file(void) +{ + cierra(); +} +//****************************************************************************************************************** +BOOL Cb_file::abre( char* path,int modo,BOOL sobre_escri , BOOL shared) +{ + int fl; + int fl1; + int fl2=0; + if(shared) + fl2=FILE_SHARE_READ; + if (modo==1) + { + fl=GENERIC_READ; + fl1=OPEN_EXISTING; + } + else if (modo==2) + { + fl=GENERIC_WRITE; + if (sobre_escri) + fl1=CREATE_ALWAYS; + else + fl1=OPEN_ALWAYS; + } + else + { + fl=GENERIC_READ | GENERIC_WRITE; + fl1=OPEN_ALWAYS; + if (sobre_escri) + fl1=CREATE_ALWAYS; + else + fl1=OPEN_ALWAYS; + } + + hfile = CreateFile(path, fl, fl2, NULL, + fl1, FILE_ATTRIBUTE_NORMAL, 0); + + if (hfile == INVALID_HANDLE_VALUE) + { + if (er) + er->pon_win("Cb_file"); + return FALSE; + } + return TRUE; +} +//****************************************************************************************************************** +QWORD Cb_file::size() +{ + if (!irAini()) + return 0; + if (!irAfin()) + return 0; + return dw; + +} +//****************************************************************************************************************** \ No newline at end of file diff --git a/b_file.h b/b_file.h new file mode 100644 index 0000000..7926eed --- /dev/null +++ b/b_file.h @@ -0,0 +1,175 @@ +#pragma once +#include "base_head.h" +#include "_error.h" +#include "utiles_def.h" +class UTILES_EXPORT Cb_file: public IdataTransfer//manejo de archivos binarios +{ +private: + HANDLE hfile;//hanled del archivo + LARGE_INTEGER li;//se usa para dividir enteros de 64 + DWORD dw;//bites movidos y respuestas al escribir +public: + C_error *er; + + Cb_file(void); + ~Cb_file(void); + //****************************************************************************************************************** + //funciones-------------------------------------------------------------------- + //****************************************************************************************************************** + inline BOOL abierto() + { + return hfile != INVALID_HANDLE_VALUE; + }; + //****************************************************************************************************************** + BOOL abre(char* path,int modo, BOOL sobre_escri=FALSE, BOOL shared=FALSE);//modo 1 lectura modo 2 escritura modo 3 ambos + //****************************************************************************************************************** + inline void cierra()//cierra archivo; + { + if (hfile != INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + } + } + //****************************************************************************************************************** + QWORD size();//te devuelve el tamaño del archivo en bytes + //****************************************************************************************************************** + inline BOOL lee(void* buf,int nb)//lee un numero de bites y lo pone en buf + { + if (!ReadFile(hfile, (LPSTR) buf ,nb,&dw,NULL)) + { + if (er) + er->pon_win("Cb_file"); + //cierra--------------------- + if (hfile != INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + } + //--------------------------- + return FALSE; + } + return TRUE; + } + //****************************************************************************************************************** + inline BOOL escribe(void* buf,int nb)//escribe numero de bites + { + if (!WriteFile(hfile, (LPSTR) buf ,nb,&dw,NULL)) + { + if (er) + er->pon_win("Cb_file"); + //cierra--------------------- + if (hfile != INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + } + //--------------------------- + return FALSE; + } + return TRUE; + } + //****************************************************************************************************************** + inline BOOL irAfin()//va a la posicion del final del archivo + { + dw=SetFilePointer(hfile,0,NULL,FILE_END); + if(dw==INVALID_SET_FILE_POINTER) + { + if (er) + er->pon_win("Cb_file"); + //cierra--------------------- + if (hfile != INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + } + //--------------------------- + return FALSE; + } + return TRUE; + } + //****************************************************************************************************************** + BOOL irAini(int nb=0)//va al inicio del archivo + nb bytes; + { + + dw=SetFilePointer(hfile,nb,NULL,FILE_BEGIN); + if(dw==INVALID_SET_FILE_POINTER) + { + if (er) + er->pon_win("Cb_file"); + //cierra--------------------- + if (hfile != INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + } + //--------------------------- + return FALSE; + } + return TRUE; + } + //****************************************************************************************************************** + BOOL irA(int nb=0)//salta nbites; + { + + dw=SetFilePointer(hfile,nb,NULL,FILE_CURRENT); + if(dw==INVALID_SET_FILE_POINTER) + { + if (er) + er->pon_win("Cb_file"); + //cierra--------------------- + if (hfile != INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + } + //--------------------------- + return FALSE; + } + return TRUE; + } + //****************************************************************************************************************** + inline BOOL irAini( QWORD nb)//entero de 64 bytes + { + li.QuadPart = nb; + dw=SetFilePointer(hfile,li.LowPart,&li.HighPart,FILE_BEGIN); + if(dw==INVALID_SET_FILE_POINTER) + { + if (er) + er->pon_win("Cb_file"); + //cierra--------------------- + if (hfile != INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + } + //--------------------------- + return FALSE; + } + return TRUE; + } + + virtual __int64 getNB_it() + { + return size(); + } + + virtual __int64 getNext_it( void* buf,__int64 nb ) + { + if(lee(buf,(int)nb)) + return nb; + return -1; + } + + virtual bool setPosition_it( __int64 nb ) + { + return irAini((int)nb) ==TRUE; + } + + virtual bool set_it( void* buf, __int64 nb ) + { + return escribe(buf,(int)nb) == TRUE; + } + //****************************************************************************************************************** + +}; diff --git a/base_head.h b/base_head.h new file mode 100644 index 0000000..cc9ff00 --- /dev/null +++ b/base_head.h @@ -0,0 +1,20 @@ +#pragma once + +#ifndef UTILES_EXPORT +#ifdef _WINDLL +#define UTILES_EXPORT __declspec(dllexport) +#else +#define UTILES_EXPORT __declspec(dllimport) +#endif +#endif + +#include +#define UINT16_MAX 0xffff +#ifdef _WIN64 +typedef __int64 ssize_t; +#else +typedef _w64 int ssize_t; + +#endif + +#pragma warning(disable:4996) diff --git a/bmp_control.cpp b/bmp_control.cpp new file mode 100644 index 0000000..88b9180 --- /dev/null +++ b/bmp_control.cpp @@ -0,0 +1,428 @@ + +#include "stdafx.h" +#include "bmp_control.h" +//#include +#include +#include + +#define ALINEAMIENTO_DWORDEX(x) ((x+4)&~4) +#define ALINEAMIENTO_DWORD(x) ((x+3)&~3) +#define WIDTHBYTES(i) ((i+31)/32*4) +//************************************************************************************** +Cbmp_control::Cbmp_control(int cx, int cy) +{ + ancho=cx; alto=cy; + bmp_info=(BITMAPINFO*)new char[sizeof(BITMAPINFOHEADER)]; + bmp_info->bmiHeader.biSize=sizeof(BITMAPINFOHEADER); + bmp_info->bmiHeader.biWidth=cx; + bmp_info->bmiHeader.biHeight=cy; + bmp_info->bmiHeader.biPlanes=1; + + bmp_info->bmiHeader.biBitCount=16; + bmp_info->bmiHeader.biCompression=0; + bmp_info->bmiHeader.biSizeImage=0; + bmp_info->bmiHeader.biXPelsPerMeter=0; + bmp_info->bmiHeader.biYPelsPerMeter=0; + bmp_info->bmiHeader.biClrUsed=0; + bmp_info->bmiHeader.biClrImportant=0; + + bmp_info->bmiHeader.biCompression=BI_RGB; +bmp_info->bmiHeader.biBitCount=32; + bits=NULL; + m_cdc=NULL; + + crea(); +} +//************************************************************************************** +Cbmp_control::~Cbmp_control() +{ + destruye(); + delete bmp_info; +} +//************************************************************************************** +void Cbmp_control::destruye() +{ + if (bits!=NULL) + { + ::SelectObject(m_hdc, m_old_bitmap); + ::DeleteObject(m_bitmap); + ::DeleteDC(m_hdc); + delete m_cdc; + m_cdc=NULL; + bits=NULL; + }; +} +//************************************************************************************** +void Cbmp_control::crea(BOOL limpiar, char ch) +{ + destruye(); + + HDC sdc=::GetDC(NULL); + m_hdc=::CreateCompatibleDC(sdc); + ::ReleaseDC(0,sdc); + LPVOID lp; + bmp_info->bmiHeader.biSizeImage = ((256 * (bmp_info->bmiHeader.biBitCount / 8) + 3) & -4) * 192; + m_bitmap=::CreateDIBSection(m_hdc,bmp_info,DIB_PAL_COLORS,&lp,NULL,NULL); + DWORD dw = GetLastError(); + bits=(BYTE*)lp; + + if (bits==NULL) + { + //ASSERT(FALSE); + //AfxMessageBox(TEXT("sin memoria!")); + ::DeleteDC(m_hdc); + m_hdc = NULL; + return; + } + m_old_bitmap=(HBITMAP)::SelectObject(m_hdc, m_bitmap); + m_cdc=new CDC(); + m_cdc->Attach(m_hdc); + if (limpiar) + rellena_bits(ch); + m_iniciado=FALSE; +} +//************************************************************************************** +/* +int GetEncoderClsid(const WCHAR* format, CLSID* pClsid) +{ + UINT num = 0; // number of image encoders + UINT size = 0; // size of the image encoder array in bytes + + Gdiplus::ImageCodecInfo* pImageCodecInfo = NULL; + + Gdiplus::GetImageEncodersSize(&num, &size); + if(size == 0) + return -1; // Failure + + pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size)); + if(pImageCodecInfo == NULL) + return -1; // Failure + + Gdiplus::GetImageEncoders(num, size, pImageCodecInfo); + + for(UINT j = 0; j < num; ++j) + { + if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 ) + { + *pClsid = pImageCodecInfo[j].Clsid; + free(pImageCodecInfo); + return j; // Success + } + } + + free(pImageCodecInfo); + return -1; // Failure +} + +BOOL Cbmp_control::guardar_bmp(char *path) +{ + + Gdiplus::Bitmap *gr=Gdiplus::Bitmap::FromHBITMAP(m_bitmap,NULL); + + // Save the altered image. + CLSID pngClsid; + GetEncoderClsid(L"image/bmp", &pngClsid); + gr->Save(L"c:\\temp\\ola.bmp",&pngClsid,NULL); + return TRUE; + +};*/ +//************************************************************************************** +void Cbmp_control::redimensiona(int cx, int cy, BOOL limpiar, char ch) +{ + if (cx!=ancho || cy!=alto) + { + ancho=cx; alto=cy; + bmp_info->bmiHeader.biWidth=cx; + bmp_info->bmiHeader.biHeight=cy; + crea(limpiar, ch); + } + else + { + if (limpiar) + rellena_bits(ch); + }; +} +//************************************************************************************** +void Cbmp_control::rellena_bits(char ch) +{ + int aaa=WIDTHBYTES(ancho*24); + int fdf=ALINEAMIENTO_DWORD(ancho*4); + if (bits!=NULL) + memset(bits, ch, alto*fdf); +} +//************************************************************************************** +void Cbmp_control::pon_bits(LPVOID src, int count) +{ + /*ASSERT(count<=alto*ALINEAMIENTO_DWORD(ancho)); + LPVOID lp=(LPVOID)bits; + count>>=2; + _asm + { + push ds; + pop es; + mov edi, dword ptr [lp]; + mov esi, dword ptr [src]; + cld; + mov ecx, count; + rep movsd; + }; + /* + if (count>Height*DWordAlign(Width)) return; + memcpy((LPVOID)Dib, src, count); + */ +} +//************************************************************************************** +HDC Cbmp_control::dame_hdc() +{ + if (bits!=NULL) return m_hdc; else return 0; + return 0; +} +//************************************************************************************** +CDC* Cbmp_control::dame_cdc() +{ + if (bits!=NULL) + return m_cdc; + else + return NULL; + return NULL; +} +//************************************************************************************** +void Cbmp_control::pinta_dib( HDC dc, CRect r ) +{ + if (bits!=NULL) + { + SetDIBitsToDevice(dc,r.left,r.top,r.Width(), + r.Height(),r.left,bmp_info->bmiHeader.biHeight-r.bottom ,0 ,bmp_info->bmiHeader.biHeight , bits, + bmp_info,DIB_RGB_COLORS); + } +} +//************************************************************************************** +void Cbmp_control::escribe_pixel(int x, int y, BYTE valor) +{ + if (bits==NULL) + return; + if (x<0 || y<0 || x>=ancho || y>=alto) + return; + + //m_bits[(m_alto-y-1)*WIDTHBYTES((m_ancho)+x)]=valor; + //m_bits[(m_alto-y-1)*WIDTHBYTES(ALINEAMIENTO_DWORD(m_ancho))+200]=valor;//WIDTHBYTES(4*((m_ancho)+(x)))]=valor; + + + //m_bits[367+ALINEAMIENTO_DWORD(x)]=valor;//WIDTHBYTES(4*((m_ancho)+(x)))]=valor; + int ff=ALINEAMIENTO_DWORD(ancho*4); + int fff=WIDTHBYTES(ancho)*8; + bits[(alto-y-1)*(ff)+x*4+0]=valor; + bits[(alto-y-1)*(ff)+x*4+1]=valor; + bits[(alto-y-1)*(ff)+x*4+2]=valor; + bits[(alto-y-1)*(ff)+x*4+3]=255; + //m_bits[sizeof(BITMAPINFOHEADER)+(m_alto-y-1)*(fff)+120]=valor; + //m_bits[(m_alto-y-1)*(ALINEAMIENTO_DWORD(m_ancho))+200]=valor;// + //m_bits[(m_alto-y-1)*(ALINEAMIENTO_DWORD(m_ancho))+200]=valor;// + //m_bits[ (y * m_ancho * 4) + (x * 4) + 0 ]=valor; +} +//************************************************************************************** +void Cbmp_control::colorea_pixel(int x, int y, BYTE valor) +{ + int res=WIDTHBYTES(ancho*24); + if (bits==NULL) + return; + if (x<0 || y<0 || x>=ancho || y>=alto) + return; + //int index=(m_alto-y-1)*ALINEAMIENTO_DWORD(m_ancho)+x; + //int index=(m_alto-y-1)*(m_ancho)+x; + bits[(alto-y-1) + 20]=valor; + bits[(alto-y-1) + 21]=valor; + //m_bits[(m_alto-y-1)*(ALINEAMIENTO_DWORD(m_ancho))+x+1]=valor+25; + //m_bits[(m_alto-y-1)*(ALINEAMIENTO_DWORD(m_ancho))+x+2]=valor+180; +} +//************************************************************************************** +void Cbmp_control::pinta_cruz(int x, int y, int ancho, BYTE color) +{ + if (bits==NULL) + return; + int i; + for (i=y-ancho; i<=y+ancho; i++) + escribe_pixel(x, i, color); + for (i=x-ancho; i<=x+ancho; i++) + escribe_pixel(i, y, color); +} +//************************************************************************************** +void Cbmp_control::mueve_datos(int cx, int cy) +{ + if (bits==NULL) + return; + LPVOID lp1, lp2; + if (cx!=0) + { // mueve datos en x + if (abs(cx)GetClientRect(&r); + rec=&r; + } + redimensiona(rec->Width(),rec->Height()); + if(!::BitBlt(m_hdc, 0, 0, ancho, alto, w->GetDC()->m_hDC, rec->left, rec->top, SRCCOPY)) + return FALSE; + return TRUE; +} +//************************************************************************************** +BOOL Cbmp_control::dib2file( char *path ) +{ + + if (bits==NULL) + { + return FALSE; + } + + BOOL result = FALSE; + PICTDESC pd; + + pd.cbSizeofstruct = sizeof(PICTDESC); + pd.picType = PICTYPE_BITMAP; + pd.bmp.hbitmap = m_bitmap; + pd.bmp.hpal = 0; + + LPPICTURE picture; + HRESULT res = OleCreatePictureIndirect(&pd, IID_IPicture, false, + reinterpret_cast(&picture)); + + if (!SUCCEEDED(res)) + return FALSE; + + LPSTREAM stream; + res = CreateStreamOnHGlobal(0, true, &stream); + + if (!SUCCEEDED(res)) + { + picture->Release(); + return FALSE; + } + + LONG bytes_streamed; + res = picture->SaveAsFile(stream, true, &bytes_streamed); + + HANDLE file = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, 0, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + + if (!SUCCEEDED(res) || !file) + { + stream->Release(); + picture->Release(); + return FALSE; + } + + HGLOBAL mem = 0; + GetHGlobalFromStream(stream, &mem); + LPVOID data = GlobalLock(mem); + + DWORD bytes_written; + + result = !!WriteFile(file, data, bytes_streamed, &bytes_written, 0); + result &= (bytes_written == static_cast(bytes_streamed)); + + GlobalUnlock(mem); + CloseHandle(file); + + stream->Release(); + picture->Release(); + + return result; + + + + + + + + + // Free memory. + + + + + + /*BITMAPINFO bi; + ZeroMemory(&bi, sizeof(BITMAPINFO)); + bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + bi.bmiHeader.biWidth = ancho; + bi.bmiHeader.biHeight = alto; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biBitCount = 24;*/ + + /*BITMAPFILEHEADER bh; + ZeroMemory(&bh, sizeof(BITMAPFILEHEADER)); + bh.bfType = 0x4d42; //bitmap + bh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); + bh.bfSize = bh.bfOffBits + ((alto*ancho)*3); + + CFile file; + if(!file.Open(path, CFile::modeCreate | CFile::modeWrite)) + { + return FALSE; + } + file.Write(&bh, sizeof(BITMAPFILEHEADER)); + file.Write(&(bmp_info->bmiHeader), sizeof(BITMAPINFOHEADER)); + file.Write(bits, 3 * alto*ancho); + file.Close();*/ + //return TRUE; +} +//************************************************************************************** +BOOL Cbmp_control::w2file(CWnd *w,char* path, CRect *rec) +{ + CRect r; + if (!rec) + { + w->GetClientRect(&r); + rec=&r; + } + + Cbmp_control cnt(rec->Width(),rec->Height()); + cnt.pon_iniciado(TRUE); + return cnt.w2dib(w,rec) && cnt.dib2file(path); + +} +//************************************************************************************** diff --git a/bmp_control.h b/bmp_control.h new file mode 100644 index 0000000..2bae0db --- /dev/null +++ b/bmp_control.h @@ -0,0 +1,102 @@ + +#pragma once +#include "base_head.h" +//bmp para pintar graficos antes de pintarlos en pantalla +//asi se evita el parpadeo +class UTILES_EXPORT Cbmp_control//falta revisar +{ + public: + //variables------------------------------------- + BYTE* bits;//bits del bmp + int ancho;//ancho en pixel del bmp + int alto;//alto en pixel del bmp + BITMAPINFO* bmp_info; + HDC m_hdc; + CDC *m_cdc; + HBITMAP m_bitmap, m_old_bitmap; + BOOL m_iniciado; + //c y de------------------------------------------ + Cbmp_control(int cx, int cy); + ~Cbmp_control(); + //funciones--------------------------------------- + void pinta_dib(HDC dc, CRect r);//pinta lo dibujado en el bmp en el hdc pasado + BOOL dib2file(char *path);//guarda el bmp en un archivo + BOOL w2dib( CWnd *w, CRect *rec=NULL, DWORD flags=PRF_CLIENT);//copia la pantalla al bmp + void redimensiona(int cx, int cy, BOOL limpiar=TRUE, char ch=0);//redimensiona el bmp + void crea(BOOL limpiar=TRUE, char ch=0);//crea bmp + void destruye();//destrulle bmp + + HDC dame_hdc();//da el hanled para pintar + CDC* dame_cdc(); + + static BOOL w2file(CWnd *w,char* path, CRect *rec=NULL);//pasa lo contenido en la ventana a un archivo de imagen + + BYTE* dame_bits(){return bits;}; + int dame_ancho(){return ancho;}; + int dame_alto(){return alto;}; + + + //BOOL guardar_bmp(char *path); + void escribe_pixel(int x, int y, BYTE valor); + void colorea_pixel(int x, int y, BYTE valor); + void pinta_cruz(int x, int y, int ancho, BYTE color); + + void rellena_bits(char ch=0); + void pon_bits(LPVOID src, int count); + + void mueve_datos(int cx, int cy); + BOOL esta_iniciado(){return m_iniciado;}; + void pon_iniciado(BOOL flag){m_iniciado=flag;}; + +public: + + + +}; + +/*void CCatchScreenDlg::SaveScreenToFile(LPCTSTR szFileName) +{ +HDC hScrDC = ::GetDC(NULL); +HDC hMemDC = NULL; + +BYTE *lpBitmapBits = NULL; + +int nWidth = GetSystemMetrics(SM_CXSCREEN); +int nHeight = GetSystemMetrics(SM_CYSCREEN); + +hMemDC = ::CreateCompatibleDC(hScrDC); + +BITMAPINFO bi; +ZeroMemory(&bi, sizeof(BITMAPINFO)); +bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); +bi.bmiHeader.biWidth = nWidth; +bi.bmiHeader.biHeight = nHeight; +bi.bmiHeader.biPlanes = 1; +bi.bmiHeader.biBitCount = 24; + +HBITMAP bitmap = ::CreateDIBSection(hMemDC, &bi, DIB_RGB_COLORS, (LPVOID*)&lpBitmapBits, NULL, 0); +HGDIOBJ oldbmp = ::SelectObject(hMemDC, bitmap); + +::BitBlt(hMemDC, 0, 0, nWidth, nHeight, hScrDC, 0, 0, SRCCOPY); + +BITMAPFILEHEADER bh; +ZeroMemory(&bh, sizeof(BITMAPFILEHEADER)); +bh.bfType = 0x4d42; //bitmap +bh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); +bh.bfSize = bh.bfOffBits + ((nWidth*nHeight)*3); + +CFile file; +if(file.Open(szFileName, CFile::modeCreate | CFile::modeWrite)) +{ +file.Write(&bh, sizeof(BITMAPFILEHEADER)); +file.Write(&(bi.bmiHeader), sizeof(BITMAPINFOHEADER)); +file.Write(lpBitmapBits, 3 * nWidth * nHeight); +file.Close(); +} + +::SelectObject(hMemDC, oldbmp); +::DeleteObject(bitmap); +::DeleteObject(hMemDC); +::ReleaseDC(NULL, hScrDC); +} +*/ \ No newline at end of file diff --git a/cola_asincrona.cpp b/cola_asincrona.cpp new file mode 100644 index 0000000..239d438 --- /dev/null +++ b/cola_asincrona.cpp @@ -0,0 +1,113 @@ +#include "StdAfx.h" +#include "cola_asincrona.h" +//************************************************************************** +Ccola_asincrona::Ccola_asincrona(void) +{ + strcpy(nombre, "Cola asincrona sin nombre"); + time_sleep=20; + m_thread=NULL; + timers=NULL; + pirate=FALSE; + n_timers=max_timers=0; + ultima_tarea=FALSE; + tipo_u_tarea=0; +} +//************************************************************************** +Ccola_asincrona::~Ccola_asincrona(void) +{ + termina(); + if (timers) + { + free(timers); + } +} +//************************************************************************** +void Ccola_asincrona::procesa(int tipo, BYTE* e ) +{ + +} +//************************************************************************** +void Ccola_asincrona::inicia( int size,int cap ) +{ + tareas.inicia(cap,size+sizeof(int)); +} +//************************************************************************** +BOOL Ccola_asincrona::add(int tipo,BYTE*e ) +{ + return tareas.add(tipo,e); +} +//************************************************************************** +void Ccola_asincrona::rum() +{ + BYTE *tarea; + BYTE *contenido; + int *tipo; + Timers_cola_asincrona *tim; + while(!pirate) + { + //miramos si hay tarea-------------------------- + t=_time64(NULL); + for (int i=0; it+tim->ultimo<=t) + { + tim->ultimo=t; + procesa(tim->tipo,NULL); + } + } + tarea=tareas.get(); + if (tarea) + { + tipo=(int*)tarea; + contenido=&tarea[sizeof(int)]; + procesa(*tipo,contenido); + } + else + + Sleep(time_sleep); + } + if (ultima_tarea) + procesa(tipo_u_tarea,NULL); +} +//************************************************************************** +void Ccola_asincrona::cuida() +{ + if (max_timers<=n_timers+1) + { + max_timers+=10; + if (timers) + { + timers=(Timers_cola_asincrona*)realloc(timers,max_timers*sizeof(Timers_cola_asincrona)); + } + else + { + timers=(Timers_cola_asincrona*)malloc(max_timers*sizeof(Timers_cola_asincrona)); + } + } +} +//************************************************************************** +void Ccola_asincrona::on_timer( int t,int tipo ) +{ + cuida(); + Timers_cola_asincrona *tim=&timers[n_timers]; + //Timers_cola_asincrona *tim=&timers[n_timers*sizeof(Timers_cola_asincrona)]; + + tim->t=t; + tim->tipo=tipo; + tim->ultimo= _time64(NULL); + n_timers++; +} +//************************************************************************** +void Ccola_asincrona::termina() +{ + pirate=TRUE; + join(); +} +//************************************************************************** +void Ccola_asincrona::add_fin( int tipo ) +{ + ultima_tarea=TRUE; + tipo_u_tarea=tipo; +} +//************************************************************************** diff --git a/cola_asincrona.h b/cola_asincrona.h new file mode 100644 index 0000000..1d74641 --- /dev/null +++ b/cola_asincrona.h @@ -0,0 +1,45 @@ +#pragma once +#include "_proceso.h" +#include "static_cola.h" +#include "base_head.h" +typedef struct Timers_cola_asincrona +{ + int t; + __int64 ultimo; + int tipo; +}Timers_cola_asincrona; + +class UTILES_EXPORT Ccola_asincrona :public C_proceso +{ +public: + +private: + Cstatic_cola tareas; + __int64 t; + int n_timers; + int max_timers; + Timers_cola_asincrona* timers; + BOOL ultima_tarea;//indica si hay que hacer ultima tarea antes de desconectar + BOOL tipo_u_tarea;//tipo de ultima tarea +public: + BOOL pirate; + int time_sleep; + + + Ccola_asincrona(void); + ~Ccola_asincrona(void); + //funciones + void inicia(int size,int cap=200);//prepara cola con elementos de tamaño size y capacidad de la coloa de cap + BOOL add(int tipo,BYTE*e);//pone una tarea nueva + void on_timer(int t,int tipo);//pone una tarea cada t milesimas de segundo (solo el tipo) + virtual void rum(); + void termina();//finaliza thred cola asincrona (espera) + void add_fin(int tipo);//pone ultima tarea(antes de finalizar) + //override + void virtual procesa(int tipo, BYTE* e); + +private: + void cuida();//pide memoria para timers + + +}; diff --git a/control_usu_con.cpp b/control_usu_con.cpp new file mode 100644 index 0000000..b19101e --- /dev/null +++ b/control_usu_con.cpp @@ -0,0 +1,175 @@ +#include "StdAfx.h" +#include "control_usu_con.h" +#include "_error.h" +#include "b_file.h" +//***************************************************************** +Ccontrol_usu_con::Ccontrol_usu_con(void) +{ + na=nb=0; +} +//***************************************************************** +Ccontrol_usu_con::~Ccontrol_usu_con(void) +{ +} +//***************************************************************** +int Ccontrol_usu_con::lee( char* path, C_error *er ) +{ + return 0; +} +//***************************************************************** +BOOL Ccontrol_usu_con::guarda( char*path ,C_error *er ) +{ + /*Head_usuario_conex_0 head; + Cb_file file; + if(!file.abre(path,2,TRUE)) + { + return FALSE; + }*/ + + + return 0; +} +//***************************************************************** +int Ccontrol_usu_con::add( Usuario_conx_0 *user ) +{ + int ind; + cerrojo.entro(); + //revisa si repe------------------------ + if (get(user->nombre)) + { + cerrojo.salgo(); + return -1; + } + //lo pone en lista---------------------- + ind=pon(user); + cerrojo.salgo(); + return ind; +} +//***************************************************************** +Usuario_conx_0* Ccontrol_usu_con::conecta( char*nombre, char* key,int*err ) +{ + Usuario_conx_0 *u, *user=(Usuario_conx_0*)malloc(sizeof(Usuario_conx_0)); + *err=0; + cerrojo.entro(); + u=get(nombre); + if (!u) + { + *err=1; + goto va_mal; + } + if (u->flags & FLAG_USUARIO_CONEXION_BLOQ) + { + *err=3; + goto va_mal; + } + else if ((u->flags & FLAG_USUARIO_CONEXION_EN_USO) && (u->flags & FLAG_USUARIO_CONEXION_INDI)) + { + *err=4; + goto va_mal; + } + else if (strcmp(u->clave,key)) + { + *err=2; + goto va_mal; + } + u->flags=u->flags | FLAG_USUARIO_CONEXION_EN_USO; + u->ncon++; + na++; + memcpy(user,u,sizeof(Usuario_conx_0)); + cerrojo .salgo(); + return user; +va_mal: + cerrojo .salgo(); + free(user); + return NULL; +} +//***************************************************************** +BOOL Ccontrol_usu_con::desconecta( Usuario_conx_0 *user ) +{ + Usuario_conx_0 *u; + int af,an; + cerrojo.entro(); + if (user->id>=us.n) + { + cerrojo.salgo(); + return FALSE; + } + u=&us[user->id]; + af=u->flags; + an=u->ncon-1; + *u=*user; + u->ncon=an; + if (an) + u->flags=af; + else + u->flags=af & ~FLAG_USUARIO_CONEXION_EN_USO; + na--; + cerrojo.salgo(); + free(user); + return TRUE; +} +//***************************************************************** +BOOL Ccontrol_usu_con::borra( Usuario_conx_0 *user ) +{ + cerrojo.entro(); + if (user->id>=us.n) + { + cerrojo.salgo(); + return FALSE; + } + us[user->id].flags=us[user->id].flags & FLAG_USUARIO_CONEXION_VACIO; + nb++; + cerrojo.salgo(); + return TRUE; +} +//***************************************************************** +int Ccontrol_usu_con::esta( char *nombre ) +{ + return 0; +} +//***************************************************************** +BYTE* Ccontrol_usu_con::get_copy( int*nu,int modo/*=0 */ ) +{ + return NULL; +} +//***************************************************************** +void Ccontrol_usu_con::verifica() +{ + +} +//***************************************************************** +int Ccontrol_usu_con::pon(Usuario_conx_0 *u) +{ + if (nb && us.n) + { + //hay vacios + for (int i=0; ius;//array de usuarios + Clock cerrojo;//interlock para protejer el array de usuarios + int nb;//numero de usuarios borrados; + int na;//numero de usuarios conectados; + //c y d--------------------------------------------- + Ccontrol_usu_con(void); + ~Ccontrol_usu_con(void); + //funciones----------------------------------------- + int lee(char* path, C_error *er);//carga usuarios de archivo y dice los que ha añadido + BOOL guarda(char*path ,C_error *er);//guarda los usuarios en un archivo + int pon(Usuario_conx_0 *u);//pone info del cliente en una posicion vacia de la lista (proteje antes usar) + Usuario_conx_0* get( char* nombre ); + //funciones concurrente---------- + int add(Usuario_conx_0 *user);//añade user CONCURRENTE + Usuario_conx_0* conecta(char*nombre, char* key,int*err);//pone como conectado un usuario CONCURRENTE + //err=1 usuariono existe,2 key incorrecta, 3 esta bloqueado, 4 usuario en uso + BOOL desconecta(Usuario_conx_0 *user);//desconecta un usuario CONCURRENTE + BOOL borra(Usuario_conx_0 *user);//borra usuario CONCURRENTE + int esta(char *nombre); //da el indice del usuario)(si esta) + BYTE* get_copy( int*nu,int modo=0 );//da una copia de los usuarios actuales + void verifica();//mira estado de lista y comprime si es necesario CONCURRENTE + + +}; diff --git a/csv_file.cpp b/csv_file.cpp new file mode 100644 index 0000000..3417735 --- /dev/null +++ b/csv_file.cpp @@ -0,0 +1,309 @@ +#include "StdAfx.h" +#include "csv_file.h" +#include "_error.h" +//********************************************************************************************************* +Ccsv_file::Ccsv_file( C_error* err/*=NULL*/ ) +{ + if (err) + { + b_er=FALSE; + er=err; + } + else + { + er= new C_error(); + b_er=TRUE; + } + filas.z=sizeof(Fila_csv_file); + filas.incremento=100; + incre_col=100; +} +//********************************************************************************************************* +Ccsv_file::~Ccsv_file(void) +{ + if(b_er && er) + delete er; + borra(); +} +//********************************************************************************************************* +Fila_csv_file* Ccsv_file::get_f( int i ) +{ + return (Fila_csv_file*)filas.get(i); +} +//********************************************************************************************************* +char* Ccsv_file::get( int fila,int col ) +{ + Fila_csv_file*f; + Columna_csv_file *c; + f=get_f(fila); + if (!f) + return NULL; + c=f->get(col); + if (!c) + return NULL; + return str.get(c->itex); +} +//********************************************************************************************************* +int Ccsv_file::n_col( int fil ) +{ + Fila_csv_file*f; + f=get_f(fil); + if (!f) + return -1; + return f->colum->n; +} +//********************************************************************************************************* +int Ccsv_file::n() +{ + return filas.n; +} +//********************************************************************************************************* +int Ccsv_file::add() +{ + Fila_csv_file*f; + filas.reserva(); + filas.n++; + f=get_f(filas.n-1); + f->inicia(incre_col); + f->flags=0; + return filas.n-1; +} +//********************************************************************************************************* +int Ccsv_file::add( int fila, char *valor ) +{ + Fila_csv_file*f; + Columna_csv_file *c; + f=get_f(fila); + if (!f) + return -1; + c=f->add_coun(); + str.add(valor); + c->itex=str.size()-1; + return f->colum->n-1; +} +//********************************************************************************************************* +int Ccsv_file::add( int fila, int valor ) +{ + char s[64]; + sprintf(s,"%ld",valor); + return add(fila,s); +} +//********************************************************************************************************* +int Ccsv_file::add( int fila, double valor ) +{ + char s[128]; + sprintf(s,"%ld",valor); + return add(fila,s); +} +//********************************************************************************************************* +BOOL Ccsv_file::set( int fila, int col, char* value ) +{ + Fila_csv_file*f; + Columna_csv_file *c; + f=get_f(fila); + if (!f) + return FALSE; + c= f->get(col); + if(!c) + return FALSE; + c->itex=str.size(); + str.add(value); + return TRUE; +} +//********************************************************************************************************* +BOOL Ccsv_file::set( int fila, int col, int value ) +{ + char s[64]; + sprintf(s,"%ld",value); + return set(fila,col,s); +} +//********************************************************************************************************* +BOOL Ccsv_file::set( int fila, int col, double value ) +{ + char s[128]; + sprintf(s,"%ld",value); + return set(fila,col,s); +} +//********************************************************************************************************* +void Ccsv_file::borra() +{ + Fila_csv_file*f; + for(int i=0; idel(); + } + filas.borra(); +} +//********************************************************************************************************* +BOOL Ccsv_file::lee( char *path,char separa ) +{ + char *buf=NULL; + char *s1; + char *s2; + char *s3; + int fi; + borra(); + HANDLE hfile=INVALID_HANDLE_VALUE; + DWORD dw,nb; + //abrimos archivo--------------------- + + hfile = CreateFile(path, GENERIC_READ, 0, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + + if (hfile == INVALID_HANDLE_VALUE) + { + er->pon_win(MODULO_CSV_FILE); + return FALSE; + } + + nb=SetFilePointer(hfile,0,NULL,FILE_END); + if(nb==INVALID_SET_FILE_POINTER) + { + er->pon_win(MODULO_CSV_FILE); + goto salgo; + } + buf=(char *)malloc(nb+2); + + dw=SetFilePointer(hfile,0,NULL,FILE_BEGIN); + if(dw==INVALID_SET_FILE_POINTER) + { + er->pon_win(MODULO_CSV_FILE); + goto salgo; + } + if (!ReadFile(hfile, (LPSTR) buf ,nb,&dw,NULL)) + { + er->pon_win(MODULO_CSV_FILE); + goto salgo; + } + CloseHandle(hfile); + hfile=INVALID_HANDLE_VALUE; + buf[nb]=0; + buf[nb+1]=0;//aseguramos el final de la cadena; + s1=buf; + //procesamos-------------------------------------------------- + while (*s1) + { + s2=busca_salto_linea(s1); + if (*s2) + { + *s2=0; + s2++; + while(*s2=='\r' ||*s2=='\n') + s2=s2+1; + } + //añadimos fila------------------------------------------ + fi=add(); + s3=s1; + while(*s3) + { + if (*s3==separa) + { + *s3=0; + //añadimos columna---------------------------------- + add(fi,s1); + s1=s3+1; + } + s3=s3+1; + } + s1=s2; + } + free(buf); + return TRUE; +salgo: + if (hfile!=INVALID_HANDLE_VALUE) + CloseHandle(hfile); + if (buf) + free(buf); + return FALSE; +} +//********************************************************************************************************* +BOOL Ccsv_file::guarda( char *path, char separa, BOOL ret_carro ) +{ + HANDLE hfile=INVALID_HANDLE_VALUE; + DWORD dw; + char salto='\n'; + char ret_ca='\r'; + Fila_csv_file*f; + Columna_csv_file *c; + char*st; + +/* + er->pon(MODULO_INI_FILE,"guarda: Función no implementada"); + return FALSE;*/ + //abrimos archivo------------------------------- + hfile=CreateFile(path, + GENERIC_WRITE, + 0, // exclusive access + NULL, // no security + CREATE_ALWAYS, + 0, // no overlapped I/O + NULL); // null template + + if (hfile == INVALID_HANDLE_VALUE) + { + er->pon_win(MODULO_CSV_FILE); + return FALSE; + } + //guardamos--------------------------------- + for (int i=0; icolum->n;j++) + { + c=f->get(j); + st=str.get(c->itex); + if (j!=0) + { + //ponemos separacion-------- + if(!WriteFile(hfile, &separa, 1, &dw, NULL)) + { + er->pon_win(MODULO_CSV_FILE); + goto salgo; + } + } + if(!WriteFile(hfile, st, sizeof(st), &dw, NULL)) + { + er->pon_win(MODULO_CSV_FILE); + goto salgo; + } + } + if (ret_carro) + { + if(!WriteFile(hfile, &ret_ca, 1, &dw, NULL)) + { + er->pon_win(MODULO_CSV_FILE); + goto salgo; + } + } + if(!WriteFile(hfile, &salto, 1, &dw, NULL)) + { + er->pon_win(MODULO_CSV_FILE); + goto salgo; + } + } + } + //cerramos---------------------------------- + if(hfile!=INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + } + return TRUE; + +salgo: + if(hfile!=INVALID_HANDLE_VALUE) + CloseHandle(hfile); + return FALSE; +} +//********************************************************************************************************* +char* Ccsv_file::busca_salto_linea( char* st ) +{ + char *s=st; + while(*s && *s!='\r' && *s!='\n' ) + s=s+1; + return s; +} +//************************************************************************************************* \ No newline at end of file diff --git a/csv_file.h b/csv_file.h new file mode 100644 index 0000000..383620a --- /dev/null +++ b/csv_file.h @@ -0,0 +1,79 @@ +#pragma once +#include "base_head.h" +#include "static_array.h" +#include "StrArray.h" +#define MODULO_CSV_FILE "Ccsv_file" +typedef struct Columna_csv_file +{ + int flags;//flags + int itex;//indice a texto +}Columna_csv_file; + +typedef struct Fila_csv_file +{ + int flags; + Cstatic_array *colum;//valor + //metodos----------------------- + void inicia(int incre=100) + { + colum = new Cstatic_array(sizeof(Columna_csv_file)); + colum->incremento=incre; + } + Columna_csv_file* get(int i) + { + return(Columna_csv_file*) colum->get(i); + } + Columna_csv_file* add_coun() + { + Columna_csv_file* c; + colum->reserva(); + colum->n++; + c=(Columna_csv_file*)colum->get(colum->n-1); + c->flags=0; + c->itex=0; + return c; + } + void del() + { + delete(colum); + } +}Fila_csv_file; + +class C_error; +class UTILES_EXPORT Ccsv_file +{ +private: + StrArray str; + Cstatic_array filas; + C_error *er; + BOOL b_er; + int incre_col; +public: + + Ccsv_file(C_error* err=NULL); + ~Ccsv_file(void); + //funciones------------------------------------------------------------------- + BOOL lee( char *path,char separa=';' ); + BOOL guarda( char *path, char separa, BOOL ret_carro=TRUE ); + + char* get(int fila,int col);//consigue la columna col de la fila fila + int n();//numero de filas + int n_col(int fil);//numero de columnas de la fila fil + + int add();//añade una fila (da el indice de dicha fila) + int add(int fila, char *valor);//añade una columna a la fila + int add(int fila, int valor); + int add(int fila, double valor); + + BOOL set(int fila, int col, char* value);//ojo con hacer muchos cambios (la memoria no se libera) + BOOL set(int fila, int col, int value); + BOOL set(int fila, int col, double value); + + void borra();//borra todo + + //funciones auxiliares-------------------------------------------------------- +private: + + Fila_csv_file* get_f(int i); + char* busca_salto_linea( char* st ); +}; diff --git a/dir_manager.cpp b/dir_manager.cpp new file mode 100644 index 0000000..527fcfd --- /dev/null +++ b/dir_manager.cpp @@ -0,0 +1,392 @@ +#include "StdAfx.h" +#include "utiles_def.h" +#include "dir_manager.h" +#include "_error.h" +#include "StrArray.h" +#include + +#include +//**************************************************************** + +Cdir_manager::Cdir_manager(void) +{ + dir_exe[0]=dir_datos[0]=dir_log[0]=dir_work[0]=path_conf[0]=dir_ejecucion[0]=path_ejecutable[0]=0; +} +//**************************************************************** +Cdir_manager::~Cdir_manager(void) +{ +} +//**************************************************************** +BOOL Cdir_manager::rellena_dirs_ejecucion() +{ + //char *st; + BOOL res=TRUE; + if (!_getcwd(dir_ejecucion, sizeof(dir_ejecucion))) + { + res= FALSE; + dir_ejecucion[0]=0; + } + if(!GetModuleFileName(NULL,path_ejecutable,sizeof(path_ejecutable))) + + { + path_ejecutable[0]=0; + res=FALSE; + } + return res; +} +//**************************************************************** +void Cdir_manager::absoluta( char *ruta ) +{ + char aux[256]; + if (strstr(ruta,D_WORK)) + { + strcpy(aux,dir_work); + strcat(aux,&ruta[strlen(D_WORK)]); + strcpy(ruta,aux); + return; + } + if (strstr(ruta,D_DAT)) + { + strcpy(aux,dir_datos); + strcat(aux,&ruta[strlen(D_DAT)]); + strcpy(ruta,aux); + return; + } + if (strstr(ruta,D_LOG)) + { + strcpy(aux,dir_log); + strcat(aux,&ruta[strlen(D_LOG)]); + strcpy(ruta,aux); + return; + } + if (strstr(ruta,D_APP)) + { + strcpy(aux,dir_exe); + strcat(aux,&ruta[strlen(D_APP)]); + strcpy(ruta,aux); + return; + } + if (strstr(ruta,P_CONG)) + { + strcpy(ruta,P_CONG); + return; + } +} +//******************************************************************************************* +BOOL Cdir_manager::lee_reg( char* clave, C_error *er ) +{ + HKEY hKey1; + long lRetCode,l2; + //abrimos clave---------------------------------------- + lRetCode = RegOpenKeyEx ( HKEY_CURRENT_USER,clave, 0, KEY_READ | KEY_SET_VALUE,&hKey1); + + if (lRetCode != ERROR_SUCCESS) + { + if(er) + { + er->pon_win("lee_reg"); + } + return FALSE; + } + + + l2 = 256; + //leemos carpeta + RegQueryValueEx(hKey1,"dir",0,NULL,(LPBYTE) dir_work,(LPDWORD) &l2); + //cerramos clave------------------------------------ + RegCloseKey( hKey1); + + //configuramos rutas-------------------------------- + sprintf(dir_log,"%s\\log",dir_work); + sprintf(dir_exe,"%s\\exe",dir_work); + sprintf(dir_datos,"%s\\datos",dir_work); + sprintf(path_conf,"%s\\conf.ini",dir_work); + //ponemos log--------------------------------------- + return(TRUE); +} +//******************************************************************************************* +void Cdir_manager::relativa( char *ruta ) +{ + char aux[256]; + if (dir_work[0]&&strstr(ruta,dir_work)) + { + strcpy(aux,D_WORK); + strcat(aux,&ruta[strlen(dir_work)]); + strcpy(ruta,aux); + return; + } + if (dir_datos[0]&&strstr(ruta,dir_datos)) + { + strcpy(aux,D_DAT); + strcat(aux,&ruta[strlen(dir_datos)]); + strcpy(ruta,aux); + return; + } + if (dir_log[0]&&strstr(ruta,dir_log)) + { + strcpy(aux,D_LOG); + strcat(aux,&ruta[strlen(dir_log)]); + strcpy(ruta,aux); + return; + } + if (dir_exe[0]&&strstr(ruta,dir_exe)) + { + strcpy(aux,D_APP); + strcat(aux,&ruta[strlen(dir_exe)]); + strcpy(ruta,aux); + return; + } + if (path_conf[0]&& strcmp(ruta,path_conf)==0) + { + strcpy(ruta,P_CONG); + return; + } +} +//******************************************************************************************* +char* Cdir_manager::dir_anterior( char*dir ) +{ + int n=(int)strlen(dir); + for (int i=n-1;i>0;i--) + { + if (dir[i]=='\\') + { + dir[i]=0; + break; + } + } + return dir; +} +//******************************************************************************************* +char* Cdir_manager::nombre_archivo( char *path,char*nombre ) +{ + int n=(int)strlen(path); + nombre[0]=0; + for (int i=n-1;i>0;i--) + { + if (path[i]=='\\') + { + strcpy(nombre,&path[i+1]); + break; + } + } + if(!nombre[0]) + strcpy(nombre,path); + return nombre; +} + +BOOL Cdir_manager::listar( char* dir,StrArray *files,StrArray *dirs/*=NULL*/,BOOL recursivo/*=FALSE*/,C_error *er/*=NULL */,char *omite ) +{ + BOOL poner_error=FALSE; + BOOL p_c=FALSE; + BOOL p_f=FALSE; + char str[256]; + //int k; + WIN32_FIND_DATA filedat; + HANDLE hfile; + + + if (!dir) + { + er->pon("listar","Puntero de listar nulo"); + return FALSE; + } + //vemos la info a recopilar-------------------------------------------- + if (er) + poner_error=TRUE; + if (dirs) + p_c=TRUE; + if(files) + p_f=TRUE; + + strcpy(str,dir); + if (str[strlen(str)-1] != '\\') + strcat(str,"\\"); + strcat(str,"*.*"); + hfile = FindFirstFile(str,&filedat); + + if (hfile != INVALID_HANDLE_VALUE)//existe dir + { + // existe el dir + do + { + if ((strcmp(filedat.cFileName,".") != 0) && + (strcmp(filedat.cFileName,"..") != 0)) + { + if (!omite||strcmp(omite,filedat.cFileName)!=0) + { + strcpy(str,dir); + if (str[strlen(str)-1] != '\\') + strcat(str,"\\"); + strcat(str,filedat.cFileName); + if (filedat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + if (p_c) + { + dirs->add(str); + } + + if(recursivo && !listar( str,files,dirs,recursivo,er,omite )) + { + FindClose(hfile); + return FALSE; + } + } + else if (p_f) + { + files->add(str); + } + } + } + } while (FindNextFile(hfile,&filedat)); + FindClose(hfile); + + } + else + { + if (poner_error) + er->pon_win("lista_file_dir"); + return FALSE; + } + return TRUE; +} +//******************************************************************************************* +BOOL Cdir_manager::listar_elementos( char *dir,StrArray *files,StrArray *dirs,C_error *er/*=NULL*/) +{ + return listar(dir,files,dirs,FALSE,er); +} +//******************************************************************************************* +BOOL Cdir_manager::lista_files( char *dir,StrArray *files,BOOL recursivo/*=FALSE*/,C_error *er/*=NULL*/,char *omite/*=NULL*/ ) +{ + return listar(dir,files,NULL,recursivo,er,omite); +} +//******************************************************************************************* +char* Cdir_manager::extension_archivo( char *path ) +{ + int n=(int)strlen(path)-1; + while(n>=0) + { + if (path[n]=='.') + return &path[n+1]; + n--; + + } + return NULL; +} +//****************************************************************************************************************************************** +BOOL Cdir_manager::crea_dir( char *path ) +{ + char dir[MAX_PATH]; + int i, n; + DWORD ftyp; + n = (int)strlen(path); + if (n<3) + return TRUE; + memcpy(dir, path, 3); + for (i = 3; path[i]; i++) + { + if (i >= MAX_PATH) + return FALSE; + if (path[i] == '\\') + { + dir[i] = 0; + //comprueba carpeta------------ + ftyp = GetFileAttributesA(dir); + if ((ftyp == INVALID_FILE_ATTRIBUTES) && !CreateDirectory(dir, NULL)) + return FALSE; + } + else if ((path[i] == '.')) + return TRUE; + dir[i] = path[i]; + } + dir[i] = 0; + //comprueba carpeta------------ + ftyp = GetFileAttributesA(dir); + if ((ftyp == INVALID_FILE_ATTRIBUTES) && !CreateDirectory(dir, NULL)) + return FALSE; + return TRUE; +} +//******************************************************************************************* +BOOL Cdir_manager::borra_archivos( char *paht, char *ext, BOOL recursivo /*= FALSE*/ ) +{ + StrArray lfiles; + char *f; + if(!Cdir_manager::listar(paht, &lfiles, NULL, recursivo )) + return FALSE; + for (int i = 0; ii) + { + pathDst[i] = path[i]; + if (&path[i]==c) + { + i++; + if(newext[0]=='.') + strcpy(&pathDst[i],&newext[1]); + else + strcpy(&pathDst[i],newext); + + return pathDst; + } + i++; + + } + return NULL; +} + +//******************************************************************************************* +char* Cdir_manager::getVersionFile( char *path, char *buf) +{ + DWORD verHandle = 0; + UINT size = 0; + LPBYTE lpBuffer = NULL; + //DWORD verSize = GetFileVersionInfoSize( "D:\\desa\\BIN\\x64\\debug\\utiles.dll", &verHandle); + buf[0]=0; + + char verData[1024]; + + if (GetFileVersionInfo( path, verHandle, 1024, verData)) + { + if (VerQueryValue(verData,"\\StringFileInfo\\%04x%04x\\FileDescription\\ProductName",(VOID FAR* FAR*)&lpBuffer,&size)) + { + int ii = 0; + } + if (VerQueryValue(verData,"\\",(VOID FAR* FAR*)&lpBuffer,&size)) + { + if (size) + { + VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)lpBuffer; + if (verInfo->dwSignature == 0xfeef04bd) + { + + // Doesn't matter if you are on 32 bit or 64 bit, + // DWORD is always 32 bits, so first two revision numbers + // come from dwFileVersionMS, last two come from dwFileVersionLS + sprintf(buf, "%d.%d.%d.%d", + ( verInfo->dwFileVersionMS >> 16 ) & 0xffff, + ( verInfo->dwFileVersionMS >> 0 ) & 0xffff, + ( verInfo->dwFileVersionLS >> 16 ) & 0xffff, + ( verInfo->dwFileVersionLS >> 0 ) & 0xffff + ); + return buf; + + } + } + } + } + return NULL; +} + +//******************************************************************************************* diff --git a/dir_manager.h b/dir_manager.h new file mode 100644 index 0000000..b89f7ec --- /dev/null +++ b/dir_manager.h @@ -0,0 +1,43 @@ +#pragma once +#include "base_head.h" + +class C_error; +class StrArray; +class UTILES_EXPORT Cdir_manager//clase para manejar carpetas +{ +public: + + //carpetas------------------------------------------------------- + char dir_work[FILENAME_MAX]; + char dir_exe[FILENAME_MAX]; + char dir_log[FILENAME_MAX]; + char dir_datos[FILENAME_MAX]; + //archivos------------------------------------------------------- + char path_conf[FILENAME_MAX]; + //rutas de ejecucion--------------------------------------------- + char dir_ejecucion[FILENAME_MAX]; + char path_ejecutable[FILENAME_MAX]; + //funciones------------------------------------------------------ + Cdir_manager(void); + ~Cdir_manager(void); + //funciones------------------------------------------------------ + void absoluta(char *ruta); + void relativa(char *ruta); + + BOOL lee_reg(char* clave, C_error *er=NULL); + BOOL rellena_dirs_ejecucion(); + //funciones estaticas--------------------------------------- + static char* dir_anterior(char*dir);//da el directorio anterior + static char* nombre_archivo(char *path,char*nombre);//devuelve en nombre el nombre del archivo + static char* extension_archivo(char *path);//te da la extension de un path o de un nombre de archivo + static char* cambia_extension_archivo(char *path, char *pathDst, char *newext);//te da la extension de un path o de un nombre de archivo + static BOOL crea_dir(char *path);//asegura que existe los directorios indicados + static BOOL borra_archivos(char *paht, char *ext, BOOL recursivo = FALSE);//borra archivos de una extension dada, si ext es null borra todos + //funciones de listado----------- + static BOOL listar_elementos(char *dir,StrArray *files,StrArray *dirs,C_error *er=NULL);//dice los files y las dir dentro de un dir(no recursivo) + static BOOL lista_files(char *dir,StrArray *files,BOOL recursivo=FALSE,C_error *er=NULL,char *omite=NULL); + + static BOOL listar( char* dir,StrArray *files,StrArray *dirs=NULL,BOOL recursivo=FALSE,C_error *er=NULL,char *omite=NULL );//funcion generica de listar + //devuelve version de el archivo + static char* getVersionFile(char *path, char *buf);//buffer de 64 sobra +}; diff --git a/garray.h b/garray.h new file mode 100644 index 0000000..573257f --- /dev/null +++ b/garray.h @@ -0,0 +1,261 @@ + +#pragma once +#ifndef Cgarray_H +#define Cgarray_H + +#define GARRAY_INCREMENT 100 +#include "b_file.h" +//array generico--------------------------------- +/* +Clase para manejar arrays genericos de cualquier tipo de clase o estructura +*/ +template +class Cgarray +{ +public: + //variables---------------------------------------------------------------------------------- + int m; //cache del array + int n; //numero de elementos en array + int increment; //valor a incrementar en la cache + T* ptr; //array de elementos + //************************************************************** + //constructores------------------------------------------------------------------------------- + //************************************************************** + Cgarray() + { + m=0; + ptr=NULL; + n=0; + increment=GARRAY_INCREMENT; + }; + //************************************************************** + Cgarray(int cache)//constructor poniendo en memoria posiciones + { + m=cache; + ptr=(T*)malloc(sizeof(T)*m); + if (ptr) + memset(ptr,0,m * sizeof(T)); + else + m=0; + n=0; + increment=GARRAY_INCREMENT; + }; + //************************************************************** + ~Cgarray() + { + if (ptr) + free(ptr); + }; + //************************************************************** + //funciones----------------------------------------------------------------------------------- + //************************************************************** + inline T& operator[](int i)//da el elemento i-esimo por referencia + { + return ptr[i]; + }; + //************************************************************** + inline T* get(int i)//da el elemento i-esimo + { + return &ptr[i] ; + }; + //************************************************************** + inline void remove(int ini, int nelem = 1) + { + if(ini<0) + ini =0; + if(ini>=n || nelem<1) + return; + int fin = ini+nelem; + if(fin>=n) + { + n =ini; + return; + } + + memmove(&ptr[ini], &ptr[fin], (n-fin)*sizeof(T)); + n-=(fin-ini); + }; + //************************************************************** + inline BOOL operator+(T &e )//añade nuevo elemento + { + T*pp; + if (m0) + { + if (inc &e) //añade una lista entera + { + int inc=n+e.n-m; + T*pp; + if (inc>0) + { + if (inc *e) //añade una lista entera + { + int inc=n+e->n-m; + T*pp; + if (inc>0) + { + if (incptr,e.n*sizeof(T)); + n+=e->n; + return TRUE ; + };*/ + //************************************************************** + inline BOOL add(T *e, int ne) //añade una lista de elementos + { + int inc=n+ne-m; + if (!e || ne<=0) + return FALSE; + T*pp; + if (inc>0) + { + if (incescribe(&n,sizeof(n))) + return FALSE; + if(!file->escribe(ptr,n*sizeof(T))) + return FALSE; + return TRUE; + } + //************************************************************** + inline BOOL leer(Cb_file *file)//lee de archivo el array + { + int nn; + if(!file->lee(&nn,sizeof(n))) + return FALSE; + if( nn<=0 || !((*this)+=nn)) + return FALSE; + if(!file->lee(&ptr[n],nn*sizeof(T))) + return FALSE; + n+=nn; + return TRUE; + } + //************************************************************** +}; +#endif \ No newline at end of file diff --git a/garray_cicli.h b/garray_cicli.h new file mode 100644 index 0000000..9d03cd4 --- /dev/null +++ b/garray_cicli.h @@ -0,0 +1,95 @@ +#pragma once +//array ciclico (al añadir si no entran mas tira por detras) +template +class Cgarray_cicli +{ +public: + //variables----------------------------------------------------- + int max_elem;//indica el maximo de elementos que puede almacenar + int n;//indica el numero de elementos almacenados + int m;//capacidad actual del array + int ini;//indice al primer elemento; + int increment; //incremento para pedir memo + T* ptr; //array de elementos + //c y d---------------------------------------------------------- + //******************************************************* + Cgarray_cicli(void) + { + ptr=NULL; + increment=100; + ini=0; + m=n=0; + max_elem=0; + }; + //******************************************************* + ~Cgarray_cicli(void) + { + if (ptr) + free(ptr); + }; + //******************************************************* + inline BOOL inicia(int maxi)//inicia la lista poniendo el maximo de elementos que puede almacenar + { + if (maxi<=0) + return FALSE; + max_elem=maxi; + n=0; + ini=0; + if (ptr) + free(ptr); + ptr=(T*)malloc(sizeof(T)*m); + if (!ptr) + { + max_elem=0; + return FALSE; + } + return TRUE; + }; + //******************************************************* + inline T* operator[](int i)//da el elemento i-esimo + { + if (max_elem<=0 || i<=0 || i>=n) + return NULL; + return &ptr[(ini+i)%max_elem]; + }; + //******************************************************* + inline BOOL operator+(T &e )//añade nuevo elemento + { + if (max_elem<=0|| !ptr) + return FALSE; + if (n==max_elem)//esta lleno, pone al inicio----- + { + memcpy(&ptr[ini],&e,sizeof(T)); + ini=(ini+1)%max_elem; + return TRUE; + } + //revisa memoria--------------------------------- + if (m +class Cgarray_ord +{ +public: + Cgarray ind; + Cgarray dat; +public: + int (*f_ord)(T1* e1,T1*e2);//resultado de comparar e1 con e2 + int (*fcomp)( T2 * t, T1*e);//resultado de comparar t con e + int modo; + //************************************************************** + Cgarray_ord(){f_ord=NULL; fcomp=NULL;modo=GARRAY_O_MODO_EXACTO;}; + ~Cgarray_ord(){}; + //************************************************************** + inline T1& operator[](int i)//da el elemento i-esimo por referencia + { + return dat[ind[i]]; + }; + //************************************************************** + inline int getix(T2*index)//da el indice elemento segun indexado + { + int f=dat.n-1, i=0 ,a=-1,res; + if((fcomp==NULL)) + return -1; + if(dat.n<=0) + return -1; + //dicotomica------------------- + while(f-i>1) + { + a=(f-i)/2+i; + res=fcomp(index,get(a)); + if (res<0) + f=a; + else if (res>0) + i=a; + else + return a; + } + res=fcomp( index,get(f)); + if(res==0) + return f; + else if (res<0 && modo==GARRAY_O_MODO_MAYOR) + return f; + res=fcomp( index, get(i)); + if(res==0) + return i; + else if(res>0 && modo==GARRAY_O_MODO_MENOR) + return i; + + else if (res<0 && modo==GARRAY_O_MODO_MAYOR) + return f; + + return -1; + }; + //************************************************************** + inline T1* getx(T2*index)//da el elemento segun indexado + { + int i=getix(index); + if(i<0) + return NULL; + return dat.get(ind[i]) ; + }; + //************************************************************** + inline T1* get(int i)//da el elemento i-esimo + { + return dat.get(ind[i]) ; + }; + //************************************************************** + inline BOOL operator+(T1 &e )//añade nuevo elemento + { + int f=dat.n-1, i=0 ,a=-1,res; + if((f_ord==NULL) || !(ind+=1) || !(dat+e) ) + return FALSE; + //dicotomica------------------- + while(f-i>1) + { + a=(f-i)/2+i; + res=f_ord(&e,get(a)); + if (res<0) + f=a; + else if (res>0) + i=a; + else + f=i=a; + } + if (f<0) + { + a=0; + } + else if (i!=f || a<0) + { + res=f_ord(&e,get(f)); + if (res>0) + a=f+1; + else if (0>f_ord(&e,get(i))) + { + a=i; + } + else + a=f; + } + + if ((a)ind[0]) + ind[idi]--; + } + if(i<(ind.n-1)) + memcpy(ind.get(i), ind.get(i+1), sizeof(int)*(ind.n-i-1)); + if((idi+1)=0)&& operator-=(idi); + }; + //************************************************************** + inline void borra()//libera la memoria del array + { + ind.borra(); + dat.borra(); + } + //************************************************************** +}; +#endif \ No newline at end of file diff --git a/gcola.h b/gcola.h new file mode 100644 index 0000000..15da222 --- /dev/null +++ b/gcola.h @@ -0,0 +1,141 @@ +#pragma once +#define GARRAY_INCREMENT 100 +//cola generico--------------------------------- +//+cosas por le final +//-por el inicio +template +struct Element_Cgcola +{ + T t; + Element_Cgcola *ant; + Element_Cgcola *sig; +}; +template +class Cgcola +{ +public: + //variables---------------------------------------------------------------------------------- + int n; //numero de elementos en array + Element_Cgcola *ini; //inicio del array + Element_Cgcola *fin; //fin del array + //************************************************************** + //constructores------------------------------------------------------------------------------- + //************************************************************** + Cgcola() + { + ini=fin=NULL; + n=0; + }; + //************************************************************** + ~Cgcola() + { + borra(); + }; + //************************************************************** + //funciones----------------------------------------------------------------------------------- + //************************************************************** + virtual inline T* operator++()//da puntero al ultimo elemento + { + if (fin) + return &fin->t; + return NULL; + + }; + //************************************************************** + virtual inline T* operator--()//da puntero al primero + { + if(ini) + return &ini->t; + return NULL; + }; + //************************************************************** + virtual inline BOOL operator+(T &e )//añade al final + { + if (fin) + { + fin->sig=(Element_Cgcola*)malloc(sizeof(Element_Cgcola)); + if (!fin->sig) + return FALSE; + fin->sig->ant=fin; + fin=fin->sig; + } + else + { + fin=(Element_Cgcola*)malloc(sizeof(Element_Cgcola)); + if (!fin) + return FALSE; + ini=fin; + fin->ant=NULL; + } + fin->t=e; + fin->sig=NULL; + n++; + return TRUE ; + }; + //************************************************************** + virtual inline BOOL operator-(T &e) //añade al principio + { + if (ini) + { + ini->ant=(Element_Cgcola*)malloc(sizeof(Element_Cgcola)); + if (!ini->ant) + return FALSE; + ini->ant->sig=ini; + ini=ini->ant; + } + else + { + ini=(Element_Cgcola*)malloc(sizeof(Element_Cgcola)); + if (!ini) + return FALSE; + fin=ini; + ini->sig=NULL; + } + ini->t=e; + ini->ant=NULL; + n++; + return TRUE ; + }; + //************************************************************** + virtual inline BOOL operator+=(T* e )//da el ultimo u lo elimina + { + if (!fin) + return FALSE; + *e=fin->t; + Element_Cgcola *el=fin; + fin=fin->ant; + fin->sig=NULL; + if (!fin) + ini=fin; + free(el); + n--; + return TRUE ; + }; + //************************************************************** + virtual inline BOOL operator-=(T* e )//da el primero y lo elimina + { + if (!ini) + return FALSE; + *e=ini->t; + Element_Cgcola *el=ini; + ini=ini->sig; + if (!ini) + fin=ini; + else + ini->ant=NULL; + free(el); + n--; + return TRUE ; + }; + //************************************************************** + virtual inline void borra()//libera la memoria del array + { + while(ini) + { + fin=ini->sig; + free(ini); + ini=fin; + } + } + //************************************************************** +}; \ No newline at end of file diff --git a/gcola_con.h b/gcola_con.h new file mode 100644 index 0000000..2e9dd26 --- /dev/null +++ b/gcola_con.h @@ -0,0 +1,118 @@ +#pragma once +#include "gcola.h" +#include "lock.h" +//cola concurrente para usar con multiples thread +template +class Cgcola_con : + public Cgcola +{ +public: + //variables-------------------------------------------------------------------------------- + Clock cerrojo;//interlock para protejer la cola + int modo;//modo 0 bloqueante, modo 1 no bloqueante + //funciones-------------------------------------------------------------------------------- + //************************************************************************* + Cgcola_con(void) + :Cgcola() + { + modo=0; + }; + //************************************************************************* + virtual ~Cgcola_con(void) + { + borra(); + }; + //************************************************************************* + //************************************************************************* + virtual inline T* operator++()//da puntero al ultimo elemento + { + T* res=NULL; + if (modo) + { + if(!cerrojo.puedo()) + return NULL; + } + else + cerrojo.entro(); + res= Cgcola::operator++(); + cerrojo.salgo(); + return res; + + }; + //************************************************************************* + virtual inline T* operator--()//da puntero al primero + { + T* res=NULL; + if (modo) + { + if(!cerrojo.puedo()) + return NULL; + } + else + cerrojo.entro(); + res= Cgcola::operator--(); + cerrojo.salgo(); + return res; + }; + //************************************************************************* + virtual inline BOOL operator+(T &e )//añade al final + { + BOOL res=FALSE; + if (modo) + { + if(!cerrojo.puedo()) + return FALSE; + } + else + cerrojo.entro(); + res= Cgcola::operator+(e); + cerrojo.salgo(); + return res; + }; + //************************************************************************* + virtual inline BOOL operator-(T &e) //añade al principio + { + BOOL res=FALSE; + if (modo) + { + if(!cerrojo.puedo()) + return FALSE; + } + else + cerrojo.entro(); + res= Cgcola::operator-(e); + cerrojo.salgo(); + return res; + }; + //************************************************************************* + virtual inline BOOL operator+=(T* e )//da el ultimo y lo elimina + { + BOOL res=FALSE; + if (modo) + { + if(!cerrojo.puedo()) + return FALSE; + } + else + cerrojo.entro(); + res= Cgcola::operator+=(e); + cerrojo.salgo(); + return res; + }; + //************************************************************************* + virtual inline BOOL operator-=(T* e )//da el primero y lo elimina + { + BOOL res=FALSE; + if (modo) + { + if(!cerrojo.puedo()) + return FALSE; + } + else + cerrojo.entro(); + res= Cgcola::operator-=(e); + cerrojo.salgo(); + return res; + }; + //************************************************************************* +}; diff --git a/gconect_srv.cpp b/gconect_srv.cpp new file mode 100644 index 0000000..ef39a5e --- /dev/null +++ b/gconect_srv.cpp @@ -0,0 +1,119 @@ +#include "StdAfx.h" +#include "gconect_srv.h" + +//***************************************************************************************************************** +Cgconect_srv::Cgconect_srv(void) +{ + nconex=0; + fin=FALSE; +} +//***************************************************************************************************************** +Cgconect_srv::~Cgconect_srv(void) +{ +} +//***************************************************************************************************************** +void Cgconect_srv::log_ext( __time64_t tiemp, char *modulo, char *fmt ) +{ + Msg_evento_log m; + m.tiempo=tiemp; + strcpy(m.nivel,modulo); + strcpy(m.nivel,fmt); + inter_msg.entro(); + mens+m; + inter_msg.salgo(); +} +//***************************************************************************************************************** +Cproceso_cliente* Cgconect_srv::crea_cliente( void ) +{ + if (fin) + return NULL; + Cclient_gconect_srv *cli=new Cclient_gconect_srv(); + if (!cli) + return NULL; + + strcpy(cli->nombre, "Cliente gconex_srv"); + cli->principal = this; + nconex++; + return cli; +} +//***************************************************************************************************************** + +//***************************************************************************************************************** +void Cclient_gconect_srv::rum() +{ + int nv=0;//numero de veces esperando sin recivir nada + int nb;//numero de bytes recividos en el paquete + BOOL procesa=FALSE;//indica si hay paquetes a procesar + BYTE *buffer;//buffer donde se almacena paquete recibido + BYTE buf[256];//buffer secundario de envios + Usuario_conx_0 *usu=NULL;//usuario logeado + codifica=FALSE;//indica si la comunicacion va cifrada + while(!*soc->pirate && nv<6000 && !principal->fin) + { + //pillapaquete----------------------------------------- + if(!soc->recibe_package(0)) + { + Sleep(10); + nv++; + } + else + { + if (soc->cab.nb>0) + { + nb=soc->cab.nb; + procesa=TRUE; + codifica=0; + nv=0; + if (soc->cab.flags & FLAG_PACKAGE_HEAD_0_ENCRIPT1) + codifica=1; + } + } + if (nbfin ) + continue; + nv=0; + procesa=FALSE; + //se resta lo que ocupa el entero + nb-=sizeof(int); + if (nb>0) + buffer=&soc->buf[sizeof(int)]; + else + buffer=FALSE; + //procesa paquete------------------------------------------------------------------- + switch(*(int*)soc->buf) + { + case PETICION_GENERAL_PRESENTA: + { + break; + } + case PETICION_GENERAL_OK: + { + //theApp.log.loguea(_time64(NULL),"cliente","Recivido paquete ok"); + buf[0]=PETICION_GENERAL_OK; + soc->envia_package(buf,1,codifica); + break; + } + case PETICION_GENERAL_DESCONECTA: + { + break; + } + case PETICION_GENERAL_DAME_LOG://hace falta login + { + break; + } + case PETICION_GENERAL_TOMA_COMANDO://hace falta login + { + principal->escucha->on_recivido(soc,buffer,nb); + break; + } + default://paquete desconocido se cierra socket + { + *soc->pirate=TRUE;//sale el thead + } + } + } + //descontamos thread--------------------------------------------------------- + principal->escucha->borra_cliente(this); +} +//***************************************************************************************************************** \ No newline at end of file diff --git a/gconect_srv.h b/gconect_srv.h new file mode 100644 index 0000000..e77f15b --- /dev/null +++ b/gconect_srv.h @@ -0,0 +1,57 @@ +#pragma once +#include "_log.h" +#include "garray_cicli.h" +#include "proceso_cliente.h" +#include "sock_sv.h" +//falta hacer login revision de paquetes y clase generica de usuarios +class Cclient_gconect_srv; +class UTILES_EXPORT C_escucha_conex_srv//clase para escuchar paquetes recividos en conex_srv +{ +public: + virtual void on_recivido(Csock_cl *soc, BYTE *buf, int nb)=0;//puntero a socket, puntero a paquete, numero de bytes del paquete + //para desconectar poner a true la variable pirate del soc + virtual void borra_cliente(Cclient_gconect_srv *cli)=0;//funcion en la que se entra cuando se cierra un cliente(se ha de mandar un mensaje a el principal) + //no se olvide de restar 1 al numero de thread +}; +//clase conexion entre servidores (servicios) y aplicaciones de administracion +class UTILES_EXPORT Cgconect_srv: public C_escucha_log, public Cescucha_sock_sv +{ +public: + //variables---------------------------- + Cgarray_cicli mens;//cola de mensajes de log + Clock inter_msg;//interlock para protejer cola de mensajes + Csock_sv soc_sv;//socket de escucha + C_escucha_conex_srv *escucha;//recibe paquetes de conexion si no son de log + BOOL fin;//indica si hay que irse o no; + int nconex;//indica el numero de conexiones activas en el momento + /*Clock inter_conex;//interlock para gestionar clientes + Csock_cl *soc_basura;//puntero a socket para borrar*/ + + //v y d-------------------------------- + Cgconect_srv(void); + ~Cgconect_srv(void); + + //funciones---------------------------- + + virtual void log_ext( __time64_t tiemp, char *modulo, char *fmt );//pone otro mensaje en cola + virtual Cproceso_cliente* crea_cliente( void );//funcion que crea el cliente + +}; +class UTILES_EXPORT Cclient_gconect_srv: public Cproceso_cliente//thread de clientes +{ +public: + BOOL codifica;//indica si la comunicacion va cifrada + Cgconect_srv *principal;//puntero a clase principal + virtual void rum();//funcion thead de conexion + +}; +//consejos de utilizacion----------------------------------------- +/* +crear clase y configurar interface (escucha). +configurar socket y poner en lisener. + +En el evento borra_cliente enviar un mensaje al que a creado el socket listener. +Dentro de dicho mensaje restar 1 a la variable nconex y hacer un delete al argumento de cliente + +para finalizar la aplicación poner a true la variable fin y esperar a que salgan todos los clientes conectados (nconex<=0) +*/ diff --git a/gorden.h b/gorden.h new file mode 100644 index 0000000..39a4120 --- /dev/null +++ b/gorden.h @@ -0,0 +1,250 @@ +#pragma once +#include "garray.h" + +/* +Ordenaciones de varias ordenaciones de un array +la funcion de orden f_ord(e1, e2) +ha de devolver <0 si e10 si e1>e2 +*/ +typedef struct Indices_gorden +{ + int i; //indice a a elemento con esta posicion + int io;//posicion que ocupa el elemento de la lista original en este orden +}Indices_gorden; +typedef struct Orden_gorden +{ + int (*f_ord)(void* e1, void*e2);//funcion de orden + Cgarray ind;//indices +}Orden_gorden; + +template +class Cgorden +{ +public: + //variables----------------------------------- + Cgarray ord; + Cgarray *elem; + //c y d--------------------------------------- + //************************************************************** + Cgorden(Cgarray *el=NULL) + { + elem=el; + } + //************************************************************** + ~Cgorden() + { + //borramos arrays + for (int i=0; in; + for(i=0; in; i++) + { + ii.i=i; + o.ind+ii; + } + //------------------------------- + //ordena + ord_qsort(0,elem->n-1,&o); + //reasigna---------------------------- + for(i=0; in; i++) + o.ind[o.ind[i].i]=i; + //añade el orden----------------- + + ord+o; + o.ind.ptr=NULL; + o.ind.m=0; + return TRUE; + } + //************************************************************** + inline T* get(int i, int o)//da el elemento iesimo del orden o + { + return NULL; + } + //************************************************************** + inline int geti(int i, int o)//da el indice del elemento que iesimo del orden o + { + return ord[o].ind[i].i; + } + //************************************************************** + inline int geti(int i, int o, int oi)//da el la posicion que tiene el iesimo del orden o en el orden oi + { + return ord[oi].ind[ord[o].ind[i].i].io; + } + //****************************************************************** + inline void ord_qsort(int ini, int fin, Orden_gorden *o) + { + int ii,kf,ki, jf,ji,p1,p, com; + BOOL bus=TRUE; + //caso base------------------- + p=(fin-ini); + if(p<1) + return; + if (p<2) + { + if(0f_ord(elem->get(o->ind[ini].i),elem->get(o->ind[fin].i))) + { + ii=o->ind[ini].i; + o->ind[ini].i=o->ind[fin].i; + o->ind[fin].i=ii; + } + return; + } + //a pivotar------------------- + //inicializacion + p+=ini; + p1=p; + kf=fin; + ki=ini; + jf=ji=-1; + while(bus) + { + //busca por la izquierda----- + while(p>ki) + { + com=o->f_ord(elem->get(o->ind[p].i),elem->get(o->ind[ki].i)); + if(com<0) + { + if(jf>=0) + { + ii=o->ind[jf].i; + o->ind[jf].i=o->ind[ki].i; + o->ind[ki].i=ii; + jf=-1; + ki++; + } + else + { + ji=ki;//encontrado tio que va al otro lado + break; + } + + } + else if(com==0) + { + //elementos iguales se pone al centro + p--; + ii=o->ind[p].i; + o->ind[p].i=o->ind[ki].i; + o->ind[ki].i=ii; + } + else + ki++; + } + //busca por la derecha----- + while(p1f_ord(elem->get(o->ind[p1].i),elem->get(o->ind[kf].i)); + if(com>0) + { + if(ji>=0) + { + ii=o->ind[ji].i; + o->ind[ji].i=o->ind[kf].i; + o->ind[kf].i=ii; + ji=-1; + kf--; + } + else + { + jf=kf;//encontrado tio que va al otro lado + break; + } + + } + else if(com==0) + { + //elementos iguales se pone al centro + p1++; + ii=o->ind[p1].i; + o->ind[p1].i=o->ind[kf].i; + o->ind[kf].i=ii; + } + else + kf--; + } + //condicion de fuga--- + bus=(p>ki) && (p1ki) + { + //falta la izquierda----------------- + while(p>ki) + { + com=o->f_ord(elem->get(o->ind[p].i),elem->get(o->ind[ki].i)); + if(com<0) + { + //cambia elemento al otro lado del pivote + ii=o->ind[p-1].i; + o->ind[p-1].i=o->ind[p1].i; + o->ind[p1].i=o->ind[ki].i; + o->ind[ki].i=ii; + p--; + p1--; + continue; + } + else if(com==0) + { + //elementos iguales se pone al centro + p--; + ii=o->ind[p].i; + o->ind[p].i=o->ind[ki].i; + o->ind[ki].i=ii; + continue; + } + ki++; + } + } + else + { + while(p1f_ord(elem->get(o->ind[p1].i),elem->get(o->ind[kf].i)); + if(com<0) + { + //cambia elemento al otro lado del pivote + ii=o->ind[p1+1].i; + o->ind[p1+1].i=o->ind[p].i; + o->ind[p].i=o->ind[kf].i; + o->ind[kf].i=ii; + p++; + p1++; + continue; + } + else if(com==0) + { + //elementos iguales se pone al centro + p1++; + ii=o->ind[p1].i; + o->ind[p1].i=o->ind[kf].i; + o->ind[kf].i=ii; + continue; + } + kf--; + } + } + + ord_qsort(ini, p-1, o); + ord_qsort(p1+1, fin, o); + } +}; \ No newline at end of file diff --git a/ini_file.cpp b/ini_file.cpp new file mode 100644 index 0000000..2f3b0e2 --- /dev/null +++ b/ini_file.cpp @@ -0,0 +1,451 @@ +#include "StdAfx.h" +#include "ini_file.h" +#include "_error.h" +//********************************************************************************* +Cini_file::Cini_file(C_error* err) +{ + if (err) + { + borra_error=FALSE; + er=err; + } + else + { + er= new C_error(); + borra_error=TRUE; + } + grupos.z=sizeof(Ini_file_grupo); +} +//********************************************************************************* +Cini_file::~Cini_file(void) +{ + if (er && borra_error) + { + delete er; + } + borra(); +} +//********************************************************************************* +void Cini_file::borra() +{ + Ini_file_grupo*g; + for (int i=0; iprop.borra(); + } + grupos.borra(); + str.borra(); +} +//********************************************************************************* +int Cini_file::get_grupo( char* gr ) +{ + Ini_file_grupo *g; + char*aux; + //buscamos grupo------------------------------------------------ + for (int i=0; in); + if(!(g->flags & INI_FILE_FLAGS_VACIO)&& aux && (strcmp(gr,aux)==0)) + return i; + } + //no se encontro------------------------------------------------- + return -1; +} +//********************************************************************************* +int Cini_file::geti_valor( int gr,char *pro ) +{ + Ini_file_grupo *g; + Ini_file_props *p; + char* aux; + g=(Ini_file_grupo *) grupos.get(gr); + if (!g|| (g->flags & INI_FILE_FLAGS_VACIO)) + return -1; + //buscamos entre las propiedades del grupo----------------------- + for (int i=0; iprop.n; i++) + { + p=g->get(i); + aux=str.get(p->p); + if((!(p->flags & INI_FILE_FLAGS_VACIO))&& aux && strcmp(pro,aux)==0) + return p->v; + } + //no se encontro------------------------------------------------- + return -1; +} +//********************************************************************************* +char* Cini_file::busca( char *str,char c ) +{ + int i=0; + while(str[i]) + { + if (str[i]==c) + return &str[i]; + i++; + } + //no encontrado------------------------------------------- + return NULL; +} +//********************************************************************************* + +BOOL Cini_file::lee( char *path ) +{ + char *buf=NULL; + char *ini; + char *aux; + Ini_file_grupo *g; + Ini_file_props *p; + char log_[128]; + + HANDLE hfile=INVALID_HANDLE_VALUE; + DWORD dw,nb; + //abrimos archivo--------------------- + + hfile = CreateFile(path, GENERIC_READ, 0, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + + if (hfile == INVALID_HANDLE_VALUE) + { + er->pon_win(MODULO_INI_FILE); + return FALSE; + } + + nb=SetFilePointer(hfile,0,NULL,FILE_END); + if(nb==INVALID_SET_FILE_POINTER) + { + er->pon_win(MODULO_INI_FILE); + goto salgo; + } + buf=(char *)malloc(nb+2); + + dw=SetFilePointer(hfile,0,NULL,FILE_BEGIN); + if(dw==INVALID_SET_FILE_POINTER) + { + er->pon_win(MODULO_INI_FILE); + goto salgo; + } + if (!ReadFile(hfile, (LPSTR) buf ,nb,&dw,NULL)) + { + er->pon_win(MODULO_INI_FILE); + goto salgo; + } + CloseHandle(hfile); + hfile=NULL; + buf[nb]=0; + buf[nb+1]=0;//aseguramos el final de la cadena; + ini=buscamos_grupo(buf); + //cargamos ini---------------------------- + while(*ini)//mientras no estemos en el final + { + //pillamos grupo--------------------- + + aux=busca(ini,']'); + + if (!aux) + { + break;//no mas grupos----------- + } + //añadimos grupo-------------------- + *aux=0; + g=set_coun(); + g->n=str.size(); + g->flags=0; + g->inicia(); + str.add(ini); + ini=aux+2; + + if (*ini=='\r') + ini=ini+1; + //buscamos propiedades del grupo--- + while(*ini &&*ini!='[') + { + if (*ini=='\n'||*ini==13) + { + ini=ini+1; + + if (*ini=='\r') + ini=ini+1; + } + ini=busca_prop(ini); + if (*ini=='[') + { + ini=ini+1; + break; + } + else if(!*ini) + break; + else + { + aux=ini+strlen(ini); + //añadimos propiedad------ + p=g->set_coun(); + p->flags=0; + p->p=str.size(); + str.add(ini); + ini=aux+1; + aux=busca(ini,'\n'); + if (!aux) + { + sprintf(log_,"lee: archivo ini defectuoso, no se encuentra valor de %s",str.get(p->p)); + er->pon(MODULO_INI_FILE,log_); + goto salgo; + } + *aux=0; + if (*(aux -1)==13) + { + *(aux-1)=0; + + } + p->v=str.size(); + str.add(ini); + ini=aux+1; + //quitamos retorno de carro si hay + if (*ini=='\r') + ini=ini+1; + } + } + //nos aseguramos que estamos al inicio del grupo---- + if(*ini=='[') + ini=ini+1; + + } + if (buf) + { + free(buf); + } + return TRUE; + //error al leer----------------------- +salgo: + borra(); + if(hfile!=INVALID_HANDLE_VALUE) + CloseHandle(hfile); + if (buf) + free(buf); + + return FALSE; +} +//********************************************************************************* +char* Cini_file::buscamos_grupo( char *st ) +{ + int i=0; + char busco; + busco='['; + while(st[i])//mientras no sea 0 (fin de cadeba) + { + if (st[i]==busco) + { + if (busco!='[') + busco='['; + else + return &st[i+1];//grupo encontrado + } + if (st[i]==';')//encontrado comentario + busco='\n'; + i++; + } + return &st[i]; + +} +//********************************************************************************* +Ini_file_grupo* Cini_file::set_coun() +{ + grupos.reserva(); + grupos.n++; + return (Ini_file_grupo*) &grupos.buf[grupos.z*(grupos.n-1)]; +} +//********************************************************************************* +char* Cini_file::busca_prop( char* st ) +{ + int i=0; + char busco; + busco='='; + char*resul=st; + while(st[i])//mientras no sea 0 (fin de cadeba) + { + if (st[i]==busco) + { + if (busco=='\n') + { + busco='='; + if (st[i+1]=='\r') + i++; + resul=&st[i+1]; + } + else if (busco=='=') + { + st[i]=0; + return resul;//propiedad encontrada + } + + } + if (st[i]==';')//encontrado comentario + busco='\n'; + else if(st[i]=='[')//encontrado grupo nuevo + { + if (busco!=13)//si no esta en un comentario + return &st[i]; + } + i++; + } + return &st[i]; +} +//********************************************************************************* +char* Cini_file::get( int gr,char *pro ) +{ + int val=geti_valor(gr,pro); + if (val<0) + return NULL; + return str.get(val); +} +//********************************************************************************* +char* Cini_file::get( int gr,char *pro, char *def) +{ + int val=geti_valor(gr,pro); + if (val<0) + return def; + return str.get(val); +} +//********************************************************************************* +int Cini_file::get( int gr,char *pro, int def ) +{ + int val=geti_valor(gr,pro); + if (val<0) + return def; + return atoi(str.get(val)); + +} +//********************************************************************************* +double Cini_file::get( int gr,char *pro, double def ) +{ + int val=geti_valor(gr,pro); + if (val<0) + return def; + return atof(str.get(val)); + +} +//********************************************************************************* +BOOL Cini_file::guarda( char *path ) +{ + HANDLE hfile=INVALID_HANDLE_VALUE; + DWORD dw; + int kk; + char stra[512]; + Ini_file_grupo *g; + Ini_file_props *p; +/* + er->pon(MODULO_INI_FILE,"guarda: Función no implementada"); + return FALSE;*/ + //abrimos archivo------------------------------- + hfile=CreateFile(path, + GENERIC_WRITE, + 0, // exclusive access + NULL, // no security + CREATE_ALWAYS, + 0, // no overlapped I/O + NULL); // null template + + if (hfile == INVALID_HANDLE_VALUE) + { + er->pon_win(MODULO_INI_FILE); + return FALSE; + } + //guardamos--------------------------------- + for (int i=0; iflags & INI_FILE_FLAGS_VACIO) + { + continue; + } + //grabamos nombre grupo----------------- + sprintf(stra,"[%s]\r\n",str.get(g->n)); + kk=(int)strlen(stra); + if(!WriteFile(hfile, stra, kk, &dw, NULL)) + { + er->pon_win(MODULO_INI_FILE); + goto salgo; + } + //guardamos propiedades--------------- + for(int j=0; j<(g->prop.n); j++) + { + //conseguimos propiedad----------- + p=g->get(j); + if (p->flags & INI_FILE_FLAGS_VACIO) + { + continue; + } + //grabamos propiedad-------------- + sprintf(stra,"%s=%s\r\n",str.get(p->p),str.get(p->v)); + kk=(int)strlen(stra); + if(!WriteFile(hfile, stra, kk, &dw, NULL)) + { + er->pon_win(MODULO_INI_FILE); + goto salgo; + } + } + } + //cerramos---------------------------------- + if(hfile!=INVALID_HANDLE_VALUE) + { + CloseHandle(hfile); + } + return TRUE; + +salgo: + if(hfile!=INVALID_HANDLE_VALUE) + CloseHandle(hfile); + return FALSE; +} +//********************************************************************************* +int Cini_file::add_grupo( char *gr ) +{ + int rs = grupos.n; + Ini_file_grupo* g =set_coun(); + g->n=str.size(); + g->flags=0; + g->inicia(); + str.add(gr); + return rs; +} +//********************************************************************************* +int Cini_file::add( int gr,char *pro,char *val ) +{ + //pillamos grupo------------------------- + Ini_file_grupo *g=(Ini_file_grupo *) grupos.get(gr); + if (!g|| (g->flags & INI_FILE_FLAGS_VACIO)) + { + er->pon(MODULO_INI_FILE,"add: Indice del grupo erroneo"); + return -1; + } + //añadimos prop-------------------------- + int rs=g->prop.n; + Ini_file_props*p=g->set_coun(); + p->flags=0; + p->p=str.size(); + str.add(pro); + p->v=str.size(); + str.add(val); + return rs; +} +//********************************************************************************* +int Cini_file::add( int gr,char *pro,int val ) +{ + char str[256]; + sprintf(str,"%ld",val); + return add(gr,pro,str); +} +//********************************************************************************* +int Cini_file::add( int gr,char *pro,double val ) +{ + char str[256]; + sprintf(str,"%.2f",val); + return add(gr,pro,str); +} +//********************************************************************************* +void Cini_file::dame_valor( int gr,char *pro, char* dst,char *def ) +{ + strcpy(dst, get(gr,pro,def)); +} + +//********************************************************************************* \ No newline at end of file diff --git a/ini_file.h b/ini_file.h new file mode 100644 index 0000000..0c2de1d --- /dev/null +++ b/ini_file.h @@ -0,0 +1,88 @@ +#pragma once +#include "base_head.h" +#include "StrArray.h" +#include "static_array.h" +#define INI_FILE_FLAGS_VACIO 0x0001 +#define MODULO_INI_FILE "Cini_file" +//estructuras necesarias------------------------------------------------------------------ +typedef struct Ini_file_props +{ + short flags; + int p;//propiedad + int v;//valor +}Ini_file_props; + +typedef struct Ini_file_grupo//cabecera base de la cumunicación +{ + int n; //indice a nombre + short flags; + Cstatic_array prop; + Ini_file_grupo() + { + inicia(); + n=0; + } + void inicia() + { + prop.n=prop.m=0; + prop.buf=NULL; + prop.z=sizeof(Ini_file_props); + prop.incremento=100; + } + Ini_file_props* get(int i)//da la propiedad i + { + return (Ini_file_props*) prop.get(i); + } + Ini_file_props* set_coun()//reserva para una propiedad mas y da el puntero + { + prop.reserva(); + prop.n++; + return (Ini_file_props*) &prop.buf[prop.z*(prop.n-1)]; + } +}Ini_file_grupo; + + +//------------------------------------------------------------------------------------------------------------ +class C_error; +class UTILES_EXPORT Cini_file +{ + //variables-------------------------- +private: + StrArray str; + Cstatic_array grupos; + BOOL borra_error; +public: + C_error *er; + + Cini_file(C_error* err=NULL); + ~Cini_file(void); + //funciones-------------------------- + BOOL lee(char *path_);//lee archivo ini y lo carga en memoria + + + int get_grupo(char* gr); + int geti_valor(int gr,char *pro);//devuelve el indice del str valor + + //funciones que dan el valor-------------- + char* get(int gr,char *pro);// valor en forma de char* + int get(int gr,char *pro, int def); + double get(int gr,char *pro, double def); + char* get( int gr,char *pro, char *def); + void dame_valor( int gr,char *pro, char* dst,char *def); + //funciones de escritura----------------- + void borra(); + BOOL guarda(char *path);//guarda ini cargado en memoria en un archivo; + int add_grupo(char *gr);//añade un grupo nuevo y da el indice + int add(int gr,char *pro,char *val);//añade valor de propiedad + + //sobrecarga escritura----------------- + int add(int gr,char *pro,int val);//añade valor de propiedad + int add(int gr,char *pro,double val);//añade valor de propiedad + //funciones aux------------------------ +private: + //funciones ayuda para leer + char* busca(char *st,char c);//busca en str el char c o el nulo + char* buscamos_grupo(char *st);//busca el siguiente grupo en str + char* busca_prop(char* st); + Ini_file_grupo* set_coun(); +}; diff --git a/int_array.h b/int_array.h new file mode 100644 index 0000000..6a0c928 --- /dev/null +++ b/int_array.h @@ -0,0 +1,12 @@ +#pragma once + +class Cint_array +{ +public: + int *ind; + int m; + int n; + Cint_array(void); + ~Cint_array(void); + int get(int i) +}; diff --git a/limpia.bat b/limpia.bat new file mode 100644 index 0000000..36f1393 --- /dev/null +++ b/limpia.bat @@ -0,0 +1,22 @@ +@echo off +Echo Borra ncb. +del "%~dp0"\*.ncb +Echo Borra bak +del "%~dp0"\*.bak + +Echo Borra aps +del "%~dp0"\*.aps + +Echo Borra debug. +rmdir /s /q "%~dp0"\debug" + +Echo Borra release. +rmdir /s /q "%~dp0"\release + + +rmdir /s /q "%~dp0"\x64" + + + + +pause \ No newline at end of file diff --git a/lock.cpp b/lock.cpp new file mode 100644 index 0000000..450ccc3 --- /dev/null +++ b/lock.cpp @@ -0,0 +1,98 @@ +#include "StdAfx.h" +#include "lock.h" +//************************************************************************************************ +Clock::Clock(void) +{ + cerrojo=CLOCK_ESTADO_DESBLOQUEADO; + cliente=0; + t_sleep=25; + modo=1; + if (!InitializeCriticalSectionAndSpinCount(&cerrojo1, 0x00000400) ) + modo=0; + +} +//************************************************************************************************ +Clock::~Clock(void) +{ + if (modo) + DeleteCriticalSection(&cerrojo1); +} +//************************************************************************************************ +void Clock::entro() +{ + if (modo) + { + while(TRUE) + { + try + { + EnterCriticalSection(&cerrojo1); + return; + } + catch (CException* e) + { + e->Delete(); + Sleep(t_sleep); + } + } + return; + } + long iden = GetCurrentThreadId(); + long cerrojo_ = InterlockedExchange(&cerrojo,CLOCK_ESTADO_BLOQUEADO); + while (cerrojo_ != CLOCK_ESTADO_DESBLOQUEADO) + { + if (iden==cliente) + { + break; + } + Sleep(t_sleep); + cerrojo_ = InterlockedExchange(&cerrojo,CLOCK_ESTADO_BLOQUEADO); + } + cliente=iden; +} +//************************************************************************************************ +void Clock::salgo() +{ + if (modo) + { + LeaveCriticalSection(&cerrojo1); + return; + } + if (cliente==GetCurrentThreadId()) + { + cliente=0; + InterlockedExchange(&cerrojo,CLOCK_ESTADO_DESBLOQUEADO); + } +} +//************************************************************************************************ +BOOL Clock::puedo() +{ + if (modo) + { + return TryEnterCriticalSection(&cerrojo1); + } + long iden = GetCurrentThreadId(); + long cerrojo_ = InterlockedExchange(&cerrojo,CLOCK_ESTADO_BLOQUEADO); + if (cerrojo != CLOCK_ESTADO_DESBLOQUEADO) + { + if (iden!=cliente) + { + return FALSE; + } + } + cliente=iden; + return TRUE; +} +//************************************************************************************************************************ +long lck_sum_atm(long *n, int i) +{ + long old; + do + { + old = *n; + if (old == InterlockedCompareExchange(n, old + i, old)) + return old+i; + Sleep(1); + } while (TRUE); +} +//************************************************************************************************ \ No newline at end of file diff --git a/lock.h b/lock.h new file mode 100644 index 0000000..a3036bd --- /dev/null +++ b/lock.h @@ -0,0 +1,29 @@ +#pragma once +#include "base_head.h" + +#define CLOCK_ESTADO_BLOQUEADO 1 +#define CLOCK_ESTADO_DESBLOQUEADO 0 + +class UTILES_EXPORT Clock//estructura para concurrencia +{ +public: + + long t_sleep;//tiempo de sleep en milisegundos + + Clock(void); + ~Clock(void); + + void entro();//pilla el cerrojo durmiendo si es necesario + void salgo();//libera el cerrojo + BOOL puedo();//intenta pillar el cerrojo, si ya estaba pillado devuelve false si no true + +private: + long volatile cerrojo;//variable volatile + long cliente;//id del thred que tiene el cerrojo + CRITICAL_SECTION cerrojo1; + int modo;//indica si usa cerrojo 0 o 1 + + + +}; +UTILES_EXPORT long lck_sum_atm(long *n,int i);//suma de manera atomica i a n \ No newline at end of file diff --git a/mapmatrix.cpp b/mapmatrix.cpp new file mode 100644 index 0000000..e7e37e6 --- /dev/null +++ b/mapmatrix.cpp @@ -0,0 +1,434 @@ +#include "StdAfx.h" +#include "mapmatrix.h" +#include "_log.h" +#include + +//************************************************************************************* +BOOL CmapMatFloat::lee( char *path, char *ext, BOOL mismosvect/*=TRUE*/) +{ + BOOL mal=FALSE; + for(int ic=0; ic<(int)dat.size() && !mal; ic++) + { + if(!dat[ic].lee(ic,path,ext,(int)dat.size(),mismosvect)) + mal=TRUE; + } + + return !mal; +} +//************************************************************************************* +BOOL CmapRowFloat::guarda(HeadCostConj hd, int ic, char *path , char *ext, Cgarray *bufer) +{ + HANDLE hfile = INVALID_HANDLE_VALUE; + int nb, i; + char file[MAX_PATH]; + + sprintf_s(file,MAX_PATH,"%s%06d.%s",path,ic,ext); + //crea archivo----------------------------------- + hfile = CreateFile(file, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + if (hfile == INVALID_HANDLE_VALUE) + { + i=GetLastError(); + return FALSE; + } + //graba cabecera------------ + hd.isVect=isVect; + if(isVect) + { + hd.n=(int)datv.size(); + } + else + { + hd.n=(int)dat.size(); + } + nb = sizeof(hd); + if (nb != _lwrite((int)hfile, (LPCCH)&hd, nb)) + { + goto va_mal; + } + + if(isVect) + { + //guarda las componentes del vector + nb=sizeof(float); + for(i=0;i auxbuf; + Cgarray *buff; + if(bufer) + buff = bufer; + else + buff = &auxbuf; + int nbufer= min(hd.n,1000); + if(!((*buff)+=nbufer)) + { + goto va_mal; + } + buff->n = nbufer; + //guarda componente a componente del map + int ii = 0; + for (std::map::iterator it=dat.begin(); it!=dat.end(); ++it) + { + //int aux = it->first; + (*buff)[ii].k =it->first; + (*buff)[ii].v =it->second; + ii++; + if(ii>=buff->n) + { + nb = buff->n*sizeof(MapDataFloat); + if (nb != _lwrite((int)hfile, (LPCCH) buff->ptr, nb)) + { + goto va_mal; + } + ii =0; + } + + } + if(ii>0) + { + nb = ii*sizeof(MapDataFloat); + if (nb != _lwrite((int)hfile, (LPCCH) buff->ptr, nb)) + { + goto va_mal; + } + } + } + + CloseHandle(hfile); + return TRUE; + +va_mal: + CloseHandle(hfile); + return FALSE; +} +//************************************************************************************* +//ntot solo se usa cuando es map y pasa a vector, porque se necesita cuántos elementos en total tiene que haber +BOOL CmapRowFloat::lee(int ic, char *path , char *ext, int ntot, BOOL mismosvect/*=TRUE*/, Cgarray *bufer/* = NULL*/) +{ + HANDLE hfile = INVALID_HANDLE_VALUE; + int nb, i; + char file[MAX_PATH]; + HeadCostConj hd; + Cgarray buffaux; + + sprintf_s(file,MAX_PATH,"%s%06d.%s",path,ic,ext); + //crea archivo----------------------------------- + hfile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + if (hfile == INVALID_HANDLE_VALUE) + { + i=GetLastError(); + return FALSE; + } + + //lee cabecera------------ + memset(&hd,0,sizeof(HeadCostConj)); + nb = sizeof(hd); + if (nb != _lread((int)hfile,&hd, nb)) + { + goto va_mal; + } + if(mismosvect) + isVect=hd.isVect; + + int j=0; + float d=0; + nb=sizeof(float); + dat.clear(); + datv.clear(); + + Cgarray *buff; + if(bufer) + { + bufer->n=0; + buff = bufer; + } + else + buff =&buffaux; + int nbufer= min(hd.n,1000); + + if(hd.isVect) + { + if(isVect) + { + //vector a vector + datv.reserve(hd.n); + /*for (int i = 0; iptr, nb)) + break; + + for(int ii =0; iiptr)[ii]); + + nl+=nn; + } + } + } + else + { + if(!((*buff)+=nbufer)) + { + goto va_mal; + } + buff->n=0; + + //lee componente a componente del map + int nl =0; + int nn = 0; + if(isVect) + datv.insert(datv.begin(),ntot,VALNOEXIST_FLOAT); + + for(int i=0;iptr, nb)) + break; + + for(int ii =0; ii buff; + int nbufer= min(hd.n,1000); + if(!(buff+=nbufer)) + { + goto va_mal; + } + buff.n = nbufer; + //guarda componente a componente del map + int ii = 0; + for (std::map::iterator it=dat.begin(); it!=dat.end(); ++it) + { + //int aux = it->first; + buff[ii].k=it->first; + buff[ii].v =it->second; + ii++; + + if(ii>=buff.n) + { + nb = buff.n*sizeof(MapDataInt); + + if (nb != _lwrite((int)hfile, (LPCCH) buff.ptr, nb)) + { + goto va_mal; + } + ii =0; + } + } + if(ii>0) + { + nb = ii*sizeof(MapDataInt); + if (nb != _lwrite((int)hfile, (LPCCH) buff.ptr, nb)) + { + goto va_mal; + } + } + } + + CloseHandle(hfile); + return TRUE; + +va_mal: + CloseHandle(hfile); + return FALSE; +} +//************************************************************************************* +//falta optimizar al estilo CmapRowFloat +BOOL CmapRowInt::lee(int ic, char *path , char *ext, BOOL mismosvect/*=TRUE*/) +{ + HANDLE hfile = INVALID_HANDLE_VALUE; + int nb, i; + char file[MAX_PATH]; + HeadCostConj hd; + + sprintf_s(file,MAX_PATH,"%s%06d.%s",path,ic,ext); + //crea archivo----------------------------------- + hfile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + if (hfile == INVALID_HANDLE_VALUE) + { + i=GetLastError(); + return FALSE; + } + + //lee cabecera------------ + memset(&hd,0,sizeof(HeadCostConj)); + nb = sizeof(hd); + if (nb != _lread((int)hfile,&hd, nb)) + { + goto va_mal; + } + if(mismosvect) + isVect=hd.isVect;//fuerza a que donde lee sea vect o no igual que lo que lee, o no + + int j=0; + int d=0; + nb=sizeof(int); + if(hd.isVect) + { + //lee los componentes del vector + for(i=0;i buff; + + for(int ic=ini; icdat.size(),&buff)) + mal=TRUE; + } +} +//************************************************************************************* +BOOL CmapMatFloat::leeThread( char *path, char *ext, int nthread, BOOL mismosvect/*=TRUE*/) +{ + ThMapMatFloatLee th[MAX_THREAD_LEE]; + int nth = min(nthread,MAX_THREAD_LEE); + int n = (int)ceil(dat.size()*1./nth); + int asig = 0; + int i=0; + //C_log::log("leeThread","tot %ld n %ld", dat.size(),n); + for(i=0; i +#include +#define VALNOEXIST_FLOAT (float) 1.e+30 +#define VALNOEXIST_INT (int) -1 +#include "garray.h" +#include "th.h" + +#pragma pack(8) +typedef struct HeadCostConj +{ + int ver; //versión + bool isVect; // vect o map + int n; //num de elems guardados +}HeadCostConj; +typedef struct HeadCostAng +{ + int ver; //versión + int n; //num de elems guardados +}HeadCostAng; +#pragma pack (1) +typedef struct MapDataFloat{ + int k; + float v; +}MapDataFloat; +typedef struct MapDataInt{ + int k; + int v; +}MapDataInt; +#pragma pack(16) +#define MAX_THREAD_LEE 8 +//matixFloat--------------------------------------------- +class UTILES_EXPORT CmapRowFloat +{ + +public: + //********************************* + //Variables + bool isVect; + int imin, imax; + std::map dat; + std::vector datv; + //********************************* + //Métodos + CmapRowFloat() + { + isVect = false; + imin=INT_MAX; + imax=INT_MIN; + } + ~CmapRowFloat(void) + { + } + //****************************************************** + inline void set(int i, float v) + { + + + if(isVect) + datv[i]=v; + else + { + if(v== VALNOEXIST_FLOAT) + return; + dat[i] = v; + if(iimax) + imax=i; + } + } + //****************************************************** + inline float operator[](int irow) + { + if(isVect) + return datv[irow]; + if(irow< imin || irow>imax) + return VALNOEXIST_FLOAT; + //si tiene esa clave la devuelve, si no, devuelve MAYUSCULO + std::map::iterator elem = dat.find(irow); + if(elem == dat.end()) + //no tiene la clave + return VALNOEXIST_FLOAT; + return elem->second; + } + inline void configVector(int ymax) + { + isVect = true; + dat.clear(); + + //datv.reserve(ymax); + datv.insert(datv.begin(),ymax,VALNOEXIST_FLOAT); + + bool inVector = false; + /*for (int i =0 ; i *bufer = NULL); + BOOL lee(int ic, char *path , char *ext, int ntot, BOOL mismosvect=TRUE, Cgarray *bufer = NULL); +}; +#define MAX_MEM_MAPFLOAT 1024.*1024.*300./sizeof(float) + +class UTILES_EXPORT CmapMatFloat +{ +public: + //********************************* + //Variables + std::vector dat; + + //********************************* + //Métodos + CmapMatFloat() + { + } + ~CmapMatFloat(void) + { + } + //****************************************************** + inline CmapRowFloat& operator[](int irow) + { + return dat[irow]; + } + + inline void set(int x, int y, float val) + { + if(val>= VALNOEXIST_FLOAT) + return; + + dat[x].set(y,val); + } + //ajusta los map a la memoria minima posible + inline void memAjust() + { + for(std::vector::iterator elem = dat.begin(); elem!= dat.end(); elem++) + { + elem->memAjust(); + } + } + inline void clear() + { + dat.clear(); + } + + //reparte los nvect disponibles entre los threads, poniendo las primeras filas de cada uno de vect + inline void inicializa(int xmax, int nthr, int nvect=-1) + { + dat.reserve(xmax); + bool inVector = false; + if(nvect<0) + nvect =(int)(MAX_MEM_MAPFLOAT/xmax); + + int vectthr=0,novecthr=0,iparc=0; + if(nvect=xmax) + dat[i].configVector(xmax); + else if(nvect>0) + { + if((i-iparc)=(vectthr+novecthr)) + iparc+=vectthr+novecthr; + } + } + } + BOOL lee(char *path, char *ext, BOOL mismosvect=TRUE); + BOOL leeThread( char *path, char *ext, int nthread, BOOL mismosvect/*=TRUE*/); +}; +class UTILES_EXPORT ThMapMatFloatLee: public Cth +{ +public: + CmapMatFloat *pclas; + int ini;//fila inicio + int fin;//fila fin + int ithr; + BOOL mal;//indica si ha ido bien + BOOL mismosvect; + char*path; + char*ext; + virtual void run(); +}; +class UTILES_EXPORT CmapRowInt +{ +public: + //********************************* + //Variables + std::map dat; + std::vector datv; + int imin, imax; + bool isVect; + //********************************* + //Métodos + CmapRowInt() + { + imin=INT_MAX; + imax=INT_MIN; + isVect = false; + } + ~CmapRowInt(void) + { + } + //****************************************************** + inline void set(int i, int v) + { + if(v== VALNOEXIST_INT) + return; + + if(isVect) + datv[i]=v; + else + dat[i] = v; + + if(iimax) + imax=i; + } + //****************************************************** + inline int operator[](int irow) + { + if(isVect) + return datv[irow]; + if(irow< imin || irow>imax) + return -1; + + //si tiene esa clave la devuelve, si no, devuelve MAYUSCULO + std::map::iterator elem = dat.find(irow); + if(elem == dat.end()) + //no tiene la clave + return VALNOEXIST_INT; + return elem->second; + } + //ajusta map a memoria justa + inline void memAjust() + { + + } + inline void configVector(int ymax) + { + isVect = true; + dat.clear(); + datv.insert(datv.begin(),ymax,VALNOEXIST_INT); + /*datv.reserve(ymax); + for (int i =0 ; i dat; + + //********************************* + //Métodos + CmapMatInt() + { + } + ~CmapMatInt(void) + { + } + //****************************************************** + inline CmapRowInt& operator[](int irow) + { + return dat[irow]; + } + + inline void set(int x, int y, int val) + { + if(val== VALNOEXIST_INT) + return; + dat[x].set(y,val); + } + //ajusta los map a la memoria minima posible + inline void memAjust() + { + for(std::vector::iterator elem = dat.begin(); elem!= dat.end(); elem++) + { + elem->memAjust(); + } + } + inline void clear() + { + dat.clear(); + } + + inline void inicializa(int xmax, int nthr, int nvect=-1) + { + dat.reserve(xmax); + bool inVector = false; + if(nthr<=0) + nthr=1; + if(nvect<0) + nvect =(int)(MAX_MEM_MAPINT/xmax); + int vectthr=0,novecthr=0,iparc=0; + if(nvect=xmax)//nvec>=xmax + dat[i].configVector(xmax); + else if(nvect==0) + continue; + else + { + if((i-iparc)=(vectthr+novecthr)) + iparc+=vectthr+novecthr; + } + } + } + +}; + +#endif \ No newline at end of file diff --git a/mysql/dbug.lib b/mysql/dbug.lib new file mode 100644 index 0000000..e472fbf Binary files /dev/null and b/mysql/dbug.lib differ diff --git a/mysql/dbug.pdb b/mysql/dbug.pdb new file mode 100644 index 0000000..914c2b2 Binary files /dev/null and b/mysql/dbug.pdb differ diff --git a/mysql/libmysql.dll b/mysql/libmysql.dll new file mode 100644 index 0000000..7dae6e8 Binary files /dev/null and b/mysql/libmysql.dll differ diff --git a/mysql/libmysql.lib b/mysql/libmysql.lib new file mode 100644 index 0000000..41d18fd Binary files /dev/null and b/mysql/libmysql.lib differ diff --git a/mysql/libmysql.pdb b/mysql/libmysql.pdb new file mode 100644 index 0000000..a11c6bf Binary files /dev/null and b/mysql/libmysql.pdb differ diff --git a/mysql/mysqlclient.lib b/mysql/mysqlclient.lib new file mode 100644 index 0000000..bfbc9f7 Binary files /dev/null and b/mysql/mysqlclient.lib differ diff --git a/mysql/mysqlclient.pdb b/mysql/mysqlclient.pdb new file mode 100644 index 0000000..97a9346 Binary files /dev/null and b/mysql/mysqlclient.pdb differ diff --git a/mysql/mysys.lib b/mysql/mysys.lib new file mode 100644 index 0000000..d16f528 Binary files /dev/null and b/mysql/mysys.lib differ diff --git a/mysql/mysys.pdb b/mysql/mysys.pdb new file mode 100644 index 0000000..be8536c Binary files /dev/null and b/mysql/mysys.pdb differ diff --git a/mysql/regex.lib b/mysql/regex.lib new file mode 100644 index 0000000..bb40bb7 Binary files /dev/null and b/mysql/regex.lib differ diff --git a/mysql/regex.pdb b/mysql/regex.pdb new file mode 100644 index 0000000..e2a6f07 Binary files /dev/null and b/mysql/regex.pdb differ diff --git a/mysql/strings.lib b/mysql/strings.lib new file mode 100644 index 0000000..a2b1ee8 Binary files /dev/null and b/mysql/strings.lib differ diff --git a/mysql/strings.pdb b/mysql/strings.pdb new file mode 100644 index 0000000..8ed522a Binary files /dev/null and b/mysql/strings.pdb differ diff --git a/mysql/vio.lib b/mysql/vio.lib new file mode 100644 index 0000000..f6a4d97 Binary files /dev/null and b/mysql/vio.lib differ diff --git a/mysql/vio.pdb b/mysql/vio.pdb new file mode 100644 index 0000000..de6bdab Binary files /dev/null and b/mysql/vio.pdb differ diff --git a/mysql/yassl.lib b/mysql/yassl.lib new file mode 100644 index 0000000..b356773 Binary files /dev/null and b/mysql/yassl.lib differ diff --git a/mysql/yassl.pdb b/mysql/yassl.pdb new file mode 100644 index 0000000..a480f56 Binary files /dev/null and b/mysql/yassl.pdb differ diff --git a/mysql/zlib.lib b/mysql/zlib.lib new file mode 100644 index 0000000..ccff08b Binary files /dev/null and b/mysql/zlib.lib differ diff --git a/mysql/zlib.pdb b/mysql/zlib.pdb new file mode 100644 index 0000000..ec38bdc Binary files /dev/null and b/mysql/zlib.pdb differ diff --git a/mysql_con.cpp b/mysql_con.cpp new file mode 100644 index 0000000..baeecc4 --- /dev/null +++ b/mysql_con.cpp @@ -0,0 +1,132 @@ +#include "StdAfx.h" +/* +#include "mysql_con.h" + +//********************************************************************************************************************************** +Cmysql_con::Cmysql_con(void) +{ + conn=NULL; +} +//********************************************************************************************************************************** +Cmysql_con::~Cmysql_con(void) +{ + cierra(); +} +//********************************************************************************************************************************** +BOOL Cmysql_con::contecta( char *url,char *usr,char *key, char* dbname, int puerto ) +{ + char *opt_socket_name = NULL; + unsigned int opt_flags = 0; + cierra(); + //inicia conexion--------------------------------------------- + conn = mysql_init (NULL); + if (!conn) + { + err.pon("mysql","Error al inicializar la conexión"); + return FALSE; + } + //conecta con servidor---------------------------------------- + if (!mysql_real_connect (conn, url, usr, key, + dbname, puerto, opt_socket_name, opt_flags)) + { + pon_error(); + cierra(); + return FALSE; + } + return TRUE; +} +//********************************************************************************************************************************** +void Cmysql_con::cierra() +{ + if (conn != NULL) + { + mysql_close (conn); + conn = NULL; + } +} +//********************************************************************************************************************************** +void Cmysql_con::pon_error() +{ + char resultado[255]; + if (conn != NULL) + { + sprintf(resultado, "Error %u (%s)", mysql_errno(conn), mysql_error(conn)); + err.pon("mysql",resultado); + } +} +//********************************************************************************************************************************** +BOOL Cmysql_con::envia( char *sent ) +{ + if (mysql_query(conn, sent) != 0) + { + pon_error(); + return FALSE; + } + return TRUE; +} +//********************************************************************************************************************************** +BOOL Cmysql_con::recibe() +{ + MYSQL_RES *res; + MYSQL_ROW row; + int i; + info.borra_virut(); + registros=columnas=0; + if (!conn) + { + err.pon("mysql","Sin conexion"); + return FALSE; + } + res = mysql_store_result(conn); + if (!res) + { + pon_error(); + return FALSE; + } + //registros = (int)mysql_num_rows(res); + columnas = mysql_num_fields(res); + while ((row = mysql_fetch_row(res)) != NULL) + { + registros++; + for (i = 0; i < columnas; i++) + { + if (row[i] != NULL) + info.add((char*)row[i]); + else + info.add(""); + } + } + return TRUE; +} +//********************************************************************************************************************************** +char* Cmysql_con::get( int f,int c ) +{ + if(f<0 || f>=registros || c<0 || c>=columnas) + return NULL; + return info.get(f*columnas+c); +} +//********************************************************************************************************************************** +void Cmysql_con::get( int f, int c, int *res ) +{ + char *st=get(f,c); + if (st) + *res=atoi(st); + else + *res=0; +} +//********************************************************************************************************************************** +void Cmysql_con::get( int f, int c, double *res ) +{ + char *st=get(f,c); + if (st) + *res=atof(st); + else + *res=0; +} +//********************************************************************************************************************************** +void Cmysql_con::get( int f, int c, __int64 *res ) +{ + +} +*/ +//********************************************************************************************************************************** \ No newline at end of file diff --git a/mysql_con.h b/mysql_con.h new file mode 100644 index 0000000..674653f --- /dev/null +++ b/mysql_con.h @@ -0,0 +1,40 @@ +#pragma once +/* +//poner libmysql.lib en includes +#include "mysql.h" +#include "_error.h" +#include "str_array.h" + +/* +Clase para pillar datos de mysql + +*//* +//struct MYSQL; +class UTILES_EXPORT Cmysql_con +{ +public: + + //variables-------------------------------------------------------------------------------- + C_error err; + MYSQL *conn; + Cstr_array info;//array de informacion de contestacion + int registros;//numero de registros de contestacion + int columnas;//numero de columnas de contestacion + //c y d---------------------------------------------------------------------------------- + Cmysql_con(void); + ~Cmysql_con(void); + //funciones------------------------------------------------------------------------------ + BOOL contecta( char *url,char *usr,char *key, char* dbname, int puerto ); + void cierra(); + BOOL envia( char *sent );//envia sentencia + BOOL recibe();//recive informacion rellenando el array inf columnas y filas; + char*get(int f,int c);//devuelve la informacion de la columna c fila f + void get(int f, int c, int *res); + void get(int f, int c, double *res); + void get(int f, int c, __int64 *res); + +private: + void pon_error(); + +}; +*/ \ No newline at end of file diff --git a/mysql_incl/atomic/gcc_builtins.h b/mysql_incl/atomic/gcc_builtins.h new file mode 100644 index 0000000..4600a0e --- /dev/null +++ b/mysql_incl/atomic/gcc_builtins.h @@ -0,0 +1,38 @@ +/* Copyright (C) 2008 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#define MY_ATOMIC_MODE "atomic_builtins" + +#define make_atomic_add_body(S) \ + v= __sync_fetch_and_add(a, v); +#define make_atomic_swap_body(S) \ + v= __sync_lock_test_and_set(a, v); +#define make_atomic_cas_body(S) \ + int ## S sav; \ + sav= __sync_val_compare_and_swap(a, *cmp, set); \ + if (!(ret= (sav == *cmp))) *cmp= sav; + +#ifdef MY_ATOMIC_MODE_DUMMY +#define make_atomic_load_body(S) ret= *a +#define make_atomic_store_body(S) *a= v +#define MY_ATOMIC_MODE "gcc-builtins-up" + +#else +#define MY_ATOMIC_MODE "gcc-builtins-smp" +#define make_atomic_load_body(S) \ + ret= __sync_fetch_and_or(a, 0); +#define make_atomic_store_body(S) \ + (void) __sync_lock_test_and_set(a, v); +#endif diff --git a/mysql_incl/atomic/generic-msvc.h b/mysql_incl/atomic/generic-msvc.h new file mode 100644 index 0000000..a8601e9 --- /dev/null +++ b/mysql_incl/atomic/generic-msvc.h @@ -0,0 +1,115 @@ +/* Copyright (C) 2006-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _atomic_h_cleanup_ +#define _atomic_h_cleanup_ "atomic/generic-msvc.h" + +/* + We don't implement anything specific for MY_ATOMIC_MODE_DUMMY, always use + intrinsics. + 8 and 16-bit atomics are not implemented, but it can be done if necessary. +*/ + +/* + x86 compilers (both VS2003 or VS2005) never use instrinsics, but generate + function calls to kernel32 instead, even in the optimized build. + We force intrinsics as described in MSDN documentation for + _InterlockedCompareExchange. +*/ +#ifdef _M_IX86 + +#if (_MSC_VER >= 1500) +#include +#else +C_MODE_START +/*Visual Studio 2003 and earlier do not have prototypes for atomic intrinsics*/ +LONG _InterlockedExchange (LONG volatile *Target,LONG Value); +LONG _InterlockedCompareExchange (LONG volatile *Target, LONG Value, LONG Comp); +LONG _InterlockedExchangeAdd (LONG volatile *Addend, LONG Value); +C_MODE_END + +#pragma intrinsic(_InterlockedExchangeAdd) +#pragma intrinsic(_InterlockedCompareExchange) +#pragma intrinsic(_InterlockedExchange) +#endif + +#define InterlockedExchange _InterlockedExchange +#define InterlockedExchangeAdd _InterlockedExchangeAdd +#define InterlockedCompareExchange _InterlockedCompareExchange +/* + No need to do something special for InterlockedCompareExchangePointer + as it is a #define to InterlockedCompareExchange. The same applies to + InterlockedExchangePointer. +*/ +#endif /*_M_IX86*/ + +#define MY_ATOMIC_MODE "msvc-intrinsics" +#define IL_EXCHG_ADD32(X,Y) InterlockedExchangeAdd((volatile LONG *)(X),(Y)) +#define IL_COMP_EXCHG32(X,Y,Z) InterlockedCompareExchange((volatile LONG *)(X),(Y),(Z)) +#define IL_COMP_EXCHGptr InterlockedCompareExchangePointer +#define IL_EXCHG32(X,Y) InterlockedExchange((volatile LONG *)(X),(Y)) +#define IL_EXCHGptr InterlockedExchangePointer +#define make_atomic_add_body(S) \ + v= IL_EXCHG_ADD ## S (a, v) +#define make_atomic_cas_body(S) \ + int ## S initial_cmp= *cmp; \ + int ## S initial_a= IL_COMP_EXCHG ## S (a, set, initial_cmp); \ + if (!(ret= (initial_a == initial_cmp))) *cmp= initial_a; +#define make_atomic_swap_body(S) \ + v= IL_EXCHG ## S (a, v) +#define make_atomic_load_body(S) \ + ret= 0; /* avoid compiler warning */ \ + ret= IL_COMP_EXCHG ## S (a, ret, ret); + +/* + my_yield_processor (equivalent of x86 PAUSE instruction) should be used + to improve performance on hyperthreaded CPUs. Intel recommends to use it in + spin loops also on non-HT machines to reduce power consumption (see e.g + http://softwarecommunity.intel.com/articles/eng/2004.htm) + + Running benchmarks for spinlocks implemented with InterlockedCompareExchange + and YieldProcessor shows that much better performance is achieved by calling + YieldProcessor in a loop - that is, yielding longer. On Intel boxes setting + loop count in the range 200-300 brought best results. + */ +#ifndef YIELD_LOOPS +#define YIELD_LOOPS 200 +#endif + +static __inline int my_yield_processor() +{ + int i; + for(i=0; irw) +#define my_atomic_rwlock_init(name) pthread_mutex_init(& (name)->rw, 0) +#define my_atomic_rwlock_rdlock(name) pthread_mutex_lock(& (name)->rw) +#define my_atomic_rwlock_wrlock(name) pthread_mutex_lock(& (name)->rw) +#define my_atomic_rwlock_rdunlock(name) pthread_mutex_unlock(& (name)->rw) +#define my_atomic_rwlock_wrunlock(name) pthread_mutex_unlock(& (name)->rw) +#define MY_ATOMIC_MODE "mutex" +#ifndef MY_ATOMIC_MODE_RWLOCKS +#define MY_ATOMIC_MODE_RWLOCKS 1 +#endif +#endif + +#define make_atomic_add_body(S) int ## S sav; sav= *a; *a+= v; v=sav; +#define make_atomic_fas_body(S) int ## S sav; sav= *a; *a= v; v=sav; +#define make_atomic_cas_body(S) if ((ret= (*a == *cmp))) *a= set; else *cmp=*a; +#define make_atomic_load_body(S) ret= *a; +#define make_atomic_store_body(S) *a= v; + diff --git a/mysql_incl/atomic/x86-gcc.h b/mysql_incl/atomic/x86-gcc.h new file mode 100644 index 0000000..5a34bc2 --- /dev/null +++ b/mysql_incl/atomic/x86-gcc.h @@ -0,0 +1,69 @@ +/* Copyright (C) 2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + XXX 64-bit atomic operations can be implemented using + cmpxchg8b, if necessary. Though I've heard that not all 64-bit + architectures support double-word (128-bit) cas. +*/ + +#ifdef __x86_64__ +# ifdef MY_ATOMIC_NO_XADD +# define MY_ATOMIC_MODE "gcc-amd64" LOCK_prefix "-no-xadd" +# else +# define MY_ATOMIC_MODE "gcc-amd64" LOCK_prefix +# endif +#else +# ifdef MY_ATOMIC_NO_XADD +# define MY_ATOMIC_MODE "gcc-x86" LOCK_prefix "-no-xadd" +# else +# define MY_ATOMIC_MODE "gcc-x86" LOCK_prefix +# endif +#endif + +/* fix -ansi errors while maintaining readability */ +#ifndef asm +#define asm __asm__ +#endif + +#ifndef MY_ATOMIC_NO_XADD +#define make_atomic_add_body(S) \ + asm volatile (LOCK_prefix "; xadd %0, %1;" : "+r" (v) , "+m" (*a)) +#endif +#define make_atomic_fas_body(S) \ + asm volatile ("xchg %0, %1;" : "+r" (v) , "+m" (*a)) +#define make_atomic_cas_body(S) \ + asm volatile (LOCK_prefix "; cmpxchg %3, %0; setz %2;" \ + : "+m" (*a), "+a" (*cmp), "=q" (ret): "r" (set)) + +#ifdef MY_ATOMIC_MODE_DUMMY +#define make_atomic_load_body(S) ret=*a +#define make_atomic_store_body(S) *a=v +#else +/* + Actually 32-bit reads/writes are always atomic on x86 + But we add LOCK_prefix here anyway to force memory barriers +*/ +#define make_atomic_load_body(S) \ + ret=0; \ + asm volatile (LOCK_prefix "; cmpxchg %2, %0" \ + : "+m" (*a), "+a" (ret): "r" (ret)) +#define make_atomic_store_body(S) \ + asm volatile ("; xchg %0, %1;" : "+m" (*a), "+r" (v)) +#endif + +/* TODO test on intel whether the below helps. on AMD it makes no difference */ +//#define LF_BACKOFF ({asm volatile ("rep; nop"); 1; }) + diff --git a/mysql_incl/base64.h b/mysql_incl/base64.h new file mode 100644 index 0000000..155d669 --- /dev/null +++ b/mysql_incl/base64.h @@ -0,0 +1,49 @@ +/* Copyright (C) 2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef __BASE64_H_INCLUDED__ +#define __BASE64_H_INCLUDED__ + +#ifdef __cplusplus +extern "C" { +#endif + +/* + Calculate how much memory needed for dst of base64_encode() +*/ +int my_base64_needed_encoded_length(int length_of_data); + +/* + Calculate how much memory needed for dst of base64_decode() +*/ +int my_base64_needed_decoded_length(int length_of_encoded_data); + + +/* + Encode data as a base64 string +*/ +int my_base64_encode(const void *src, size_t src_len, char *dst); + +/* + Decode a base64 string into data +*/ +int my_base64_decode(const char *src, size_t src_len, + void *dst, const char **end_ptr); + + +#ifdef __cplusplus +} +#endif +#endif /* !__BASE64_H_INCLUDED__ */ diff --git a/mysql_incl/config-win.h b/mysql_incl/config-win.h new file mode 100644 index 0000000..9457721 --- /dev/null +++ b/mysql_incl/config-win.h @@ -0,0 +1,392 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* Defines for Win32 to make it compatible for MySQL */ + +#define BIG_TABLES + +/* + Minimal version of Windows we should be able to run on. + Currently Windows 2000 +*/ +#define _WIN32_WINNT 0x0500 + + +#if defined(_MSC_VER) && _MSC_VER >= 1400 +/* Avoid endless warnings about sprintf() etc. being unsafe. */ +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif + +#include +#include /* chmod() constants*/ +#include +#include +#include +#include +#include +#include +#include /* getpid()*/ + +#define HAVE_SMEM 1 + +#if defined(_WIN64) || defined(WIN64) +#define SYSTEM_TYPE "Win64" +#elif defined(_WIN32) || defined(WIN32) +#define SYSTEM_TYPE "Win32" +#else +#define SYSTEM_TYPE "Windows" +#endif + +#if defined(_M_IA64) +#define MACHINE_TYPE "ia64" +#elif defined(_M_IX86) +#define MACHINE_TYPE "ia32" +#elif defined(_M_ALPHA) +#define MACHINE_TYPE "axp" +#else +#define MACHINE_TYPE "unknown" /* Define to machine type name */ +#endif + +#if !(defined(_WIN64) || defined(WIN64)) +#ifndef _WIN32 +#define _WIN32 /* Compatible with old source */ +#endif +#ifndef __WIN32__ +#define __WIN32__ +#endif +#endif /* _WIN64 */ +#ifndef __WIN__ +#define __WIN__ /* To make it easier in VC++ */ +#endif + +#ifndef MAX_INDEXES +#define MAX_INDEXES 64 +#endif + +/* File and lock constants */ +#ifdef __BORLANDC__ +#define F_RDLCK LK_NBLCK /* read lock */ +#define F_WRLCK LK_NBRLCK /* write lock */ +#define F_UNLCK LK_UNLCK /* remove lock(s) */ +#else +#define F_RDLCK _LK_NBLCK /* read lock */ +#define F_WRLCK _LK_NBRLCK /* write lock */ +#define F_UNLCK _LK_UNLCK /* remove lock(s) */ +#endif + +#define F_EXCLUSIVE 1 /* We have only exclusive locking */ +#define F_TO_EOF (INT_MAX32/2) /* size for lock of all file */ +#define F_OK 0 /* parameter to access() */ +#define W_OK 2 + +#define S_IROTH S_IREAD /* for my_lib */ + +/* for MY_S_ISFIFO() macro from my_lib */ +#if defined (_S_IFIFO) && !defined (S_IFIFO) +#define S_IFIFO _S_IFIFO +#endif + +/* Winsock2 constant (Vista SDK and later)*/ +#define IPPROTO_IPV6 41 +#ifndef IPV6_V6ONLY +#define IPV6_V6ONLY 27 +#endif + +/* + Constants used by chmod. Note, that group/others is ignored + - because unsupported by Windows due to different access control model. +*/ +#define S_IRWXU S_IREAD|S_IWRITE +#define S_IRWXG 0 +#define S_IRWXO 0 +typedef int mode_t; + +#ifdef __BORLANDC__ +#define FILE_BINARY O_BINARY /* my_fopen in binary mode */ +#define O_TEMPORARY 0 +#define O_SHORT_LIVED 0 +#define SH_DENYNO _SH_DENYNO +#else +#define O_BINARY _O_BINARY /* compability with older style names */ +#define FILE_BINARY _O_BINARY /* my_fopen in binary mode */ +#define O_TEMPORARY _O_TEMPORARY +#define O_SHORT_LIVED _O_SHORT_LIVED +#define SH_DENYNO _SH_DENYNO +#endif +#define NO_OPEN_3 /* For my_create() */ + +#define SIGQUIT SIGTERM /* No SIGQUIT */ + +#undef _REENTRANT /* Crashes something for win32 */ +#undef SAFE_MUTEX /* Can't be used on windows */ + +#define LONGLONG_MIN 0x8000000000000000LL +#define LONGLONG_MAX 0x7FFFFFFFFFFFFFFFLL +#define ULONGLONG_MAX 0xFFFFFFFFFFFFFFFFULL + +/* Type information */ + +#if !defined(HAVE_UINT) +#undef HAVE_UINT +#define HAVE_UINT +typedef unsigned short ushort; +typedef unsigned int uint; +#endif /* !defined(HAVE_UINT) */ + +typedef unsigned __int64 ulonglong; /* Microsofts 64 bit types */ +typedef __int64 longlong; +#ifndef HAVE_SIGSET_T +typedef int sigset_t; +#endif +#define longlong_defined +/* + off_t should not be __int64 because of conflicts in header files; + Use my_off_t or os_off_t instead +*/ +#ifndef HAVE_OFF_T +typedef long off_t; +#endif +typedef __int64 os_off_t; +#ifdef _WIN64 +typedef UINT_PTR rf_SetTimer; +#else +typedef uint rf_SetTimer; +#endif + +#ifndef HAVE_SIZE_T +#ifndef _SIZE_T_DEFINED +typedef SIZE_T size_t; +#define _SIZE_T_DEFINED +#endif +#endif + +#ifndef HAVE_SSIZE_T +#ifndef _SSIZE_T_DEFINED +typedef SSIZE_T ssize_t; +#define _SSIZE_T_DEFINED +#endif +#endif + +#define Socket_defined +#define my_socket SOCKET +#define SIGPIPE SIGINT +#define RETQSORTTYPE void +#define QSORT_TYPE_IS_VOID +#define SOCKET_SIZE_TYPE int +#define my_socket_defined +#define byte_defined +#define HUGE_PTR +#define STDCALL __stdcall /* Used by libmysql.dll */ +#define isnan(X) _isnan(X) +#define finite(X) _finite(X) + +#ifndef UNDEF_THREAD_HACK +#define THREAD +#endif +#define VOID_SIGHANDLER +#define SIZEOF_CHAR 1 +#define SIZEOF_INT 4 +#define SIZEOF_LONG 4 +#define SIZEOF_LONG_LONG 8 +#define SIZEOF_OFF_T 8 +#ifdef _WIN64 +#define SIZEOF_CHARP 8 +#else +#define SIZEOF_CHARP 4 +#endif +#define HAVE_BROKEN_NETINET_INCLUDES +#ifdef _WIN32 +#define HAVE_NAMED_PIPE /* We can only create pipes on NT */ +#endif + +/* ERROR is defined in wingdi.h */ +#undef ERROR + +/* We need to close files to break connections on shutdown */ +#ifndef SIGNAL_WITH_VIO_CLOSE +#define SIGNAL_WITH_VIO_CLOSE +#endif + +/* All windows servers should support .sym files */ +#undef USE_SYMDIR +#define USE_SYMDIR + +/* If LOAD DATA LOCAL INFILE should be enabled by default */ +#define ENABLED_LOCAL_INFILE 1 + +/* If query profiling should be enabled by default */ +#define ENABLED_PROFILING 1 + +/* Convert some simple functions to Posix */ + +#define my_sigset(A,B) signal((A),(B)) +#define finite(A) _finite(A) +#define sleep(A) Sleep((A)*1000) +#define popen(A,B) _popen((A),(B)) +#define pclose(A) _pclose(A) + +#ifndef __BORLANDC__ +#define access(A,B) _access(A,B) +#endif + +#if !defined(__cplusplus) +#define inline __inline +#endif /* __cplusplus */ + +#ifdef _WIN64 +#define ulonglong2double(A) ((double) (ulonglong) (A)) +#define my_off_t2double(A) ((double) (my_off_t) (A)) + +#else +inline double ulonglong2double(ulonglong value) +{ + longlong nr=(longlong) value; + if (nr >= 0) + return (double) nr; + return (18446744073709551616.0 + (double) nr); +} +#define my_off_t2double(A) ulonglong2double(A) +#endif /* _WIN64 */ + +inline ulonglong double2ulonglong(double d) +{ + double t= d - (double) 0x8000000000000000ULL; + + if (t >= 0) + return ((ulonglong) t) + 0x8000000000000000ULL; + return (ulonglong) d; +} + +#if SIZEOF_OFF_T > 4 +#define lseek(A,B,C) _lseeki64((A),(longlong) (B),(C)) +#define tell(A) _telli64(A) +#endif + +#define STACK_DIRECTION -1 + +/* Difference between GetSystemTimeAsFileTime() and now() */ +#define OFFSET_TO_EPOCH 116444736000000000ULL + +#define HAVE_PERROR +#define HAVE_VFPRINT +#define HAVE_RENAME /* Have rename() as function */ +#define HAVE_BINARY_STREAMS /* Have "b" flag in streams */ +#define HAVE_LONG_JMP /* Have long jump function */ +#define HAVE_LOCKING /* have locking() call */ +#define HAVE_ERRNO_AS_DEFINE /* errno is a define */ +#define HAVE_STDLIB /* everything is include in this file */ +#define HAVE_MEMCPY +#define HAVE_MEMMOVE +#define HAVE_GETCWD +#define HAVE_TELL +#define HAVE_TZNAME +#define HAVE_PUTENV +#define HAVE_SELECT +#define HAVE_SETLOCALE +#define HAVE_SOCKET /* Giangi */ +#define HAVE_FLOAT_H +#define HAVE_LIMITS_H +#define HAVE_STDDEF_H +#define NO_FCNTL_NONBLOCK /* No FCNTL */ +#define HAVE_ALLOCA +#define HAVE_STRPBRK +#define HAVE_STRSTR +#define HAVE_COMPRESS +#define HAVE_CREATESEMAPHORE +#define HAVE_ISNAN +#define HAVE_FINITE +#define HAVE_QUERY_CACHE +#define SPRINTF_RETURNS_INT +#define HAVE_SETFILEPOINTER +#define HAVE_VIO_READ_BUFF +#if defined(_MSC_VER) && _MSC_VER >= 1400 +/* strnlen() appeared in Studio 2005 */ +#define HAVE_STRNLEN +#endif +#define HAVE_WINSOCK2 + +#define strcasecmp stricmp +#define strncasecmp strnicmp + +#ifndef _WIN32 +#undef FILE_SHARE_DELETE +#define FILE_SHARE_DELETE 0 /* Not implemented on Win 98/ME */ +#endif + +#ifdef NOT_USED +#define HAVE_SNPRINTF /* Gave link error */ +#define _snprintf snprintf +#endif + +#ifdef _MSC_VER +#define HAVE_LDIV /* The optimizer breaks in zortech for ldiv */ +#define HAVE_ANSI_INCLUDE +#define HAVE_SYS_UTIME_H +#define HAVE_STRTOUL +#endif +#define my_reinterpret_cast(A) reinterpret_cast +#define my_const_cast(A) const_cast + + +/* MYSQL OPTIONS */ + +#ifdef _CUSTOMCONFIG_ +#include +#else +#define DEFAULT_MYSQL_HOME "c:\\mysql" +#define DATADIR "c:\\mysql\\data" +#define PACKAGE "mysql" +#define DEFAULT_BASEDIR "C:\\" +#define SHAREDIR "share" +#define DEFAULT_CHARSET_HOME "C:/mysql/" +#endif +#ifndef DEFAULT_HOME_ENV +#define DEFAULT_HOME_ENV MYSQL_HOME +#endif +#ifndef DEFAULT_GROUP_SUFFIX_ENV +#define DEFAULT_GROUP_SUFFIX_ENV MYSQL_GROUP_SUFFIX +#endif + +/* File name handling */ + +#define FN_LIBCHAR '\\' +#define FN_ROOTDIR "\\" +#define FN_DEVCHAR ':' +#define FN_NETWORK_DRIVES /* Uses \\ to indicate network drives */ +#define FN_NO_CASE_SENCE /* Files are not case-sensitive */ +#define OS_FILE_LIMIT UINT_MAX /* No limit*/ + +#define DO_NOT_REMOVE_THREAD_WRAPPERS +#define thread_safe_increment(V,L) InterlockedIncrement((long*) &(V)) +#define thread_safe_decrement(V,L) InterlockedDecrement((long*) &(V)) +/* The following is only used for statistics, so it should be good enough */ +#ifdef _WIN32 /* This should also work on Win98 but .. */ +#define thread_safe_add(V,C,L) InterlockedExchangeAdd((long*) &(V),(C)) +#define thread_safe_sub(V,C,L) InterlockedExchangeAdd((long*) &(V),-(long) (C)) +#endif + +#define shared_memory_buffer_length 16000 +#define default_shared_memory_base_name "MYSQL" + +#define HAVE_SPATIAL 1 +#define HAVE_RTREE_KEYS 1 + +#define HAVE_OPENSSL 1 +#define HAVE_YASSL 1 + +#define COMMUNITY_SERVER 1 +#define ENABLED_PROFILING 1 + +#define HAVE_BOOL 1 diff --git a/mysql_incl/decimal.h b/mysql_incl/decimal.h new file mode 100644 index 0000000..530ed9e --- /dev/null +++ b/mysql_incl/decimal.h @@ -0,0 +1,107 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _decimal_h +#define _decimal_h + +typedef enum +{TRUNCATE=0, HALF_EVEN, HALF_UP, CEILING, FLOOR} + decimal_round_mode; +typedef int32 decimal_digit_t; + +typedef struct st_decimal_t { + int intg, frac, len; + my_bool sign; + decimal_digit_t *buf; +} decimal_t; + +int internal_str2dec(const char *from, decimal_t *to, char **end, + my_bool fixed); +int decimal2string(decimal_t *from, char *to, int *to_len, + int fixed_precision, int fixed_decimals, + char filler); +int decimal2ulonglong(decimal_t *from, ulonglong *to); +int ulonglong2decimal(ulonglong from, decimal_t *to); +int decimal2longlong(decimal_t *from, longlong *to); +int longlong2decimal(longlong from, decimal_t *to); +int decimal2double(decimal_t *from, double *to); +int double2decimal(double from, decimal_t *to); +int decimal_actual_fraction(decimal_t *from); +int decimal2bin(decimal_t *from, uchar *to, int precision, int scale); +int bin2decimal(const uchar *from, decimal_t *to, int precision, int scale); + +int decimal_size(int precision, int scale); +int decimal_bin_size(int precision, int scale); +int decimal_result_size(decimal_t *from1, decimal_t *from2, char op, + int param); + +int decimal_intg(decimal_t *from); +int decimal_add(decimal_t *from1, decimal_t *from2, decimal_t *to); +int decimal_sub(decimal_t *from1, decimal_t *from2, decimal_t *to); +int decimal_cmp(decimal_t *from1, decimal_t *from2); +int decimal_mul(decimal_t *from1, decimal_t *from2, decimal_t *to); +int decimal_div(decimal_t *from1, decimal_t *from2, decimal_t *to, + int scale_incr); +int decimal_mod(decimal_t *from1, decimal_t *from2, decimal_t *to); +int decimal_round(decimal_t *from, decimal_t *to, int new_scale, + decimal_round_mode mode); +int decimal_is_zero(decimal_t *from); +void max_decimal(int precision, int frac, decimal_t *to); + +#define string2decimal(A,B,C) internal_str2dec((A), (B), (C), 0) +#define string2decimal_fixed(A,B,C) internal_str2dec((A), (B), (C), 1) + +/* set a decimal_t to zero */ + +#define decimal_make_zero(dec) do { \ + (dec)->buf[0]=0; \ + (dec)->intg=1; \ + (dec)->frac=0; \ + (dec)->sign=0; \ + } while(0) + +/* + returns the length of the buffer to hold string representation + of the decimal (including decimal dot, possible sign and \0) +*/ + +#define decimal_string_size(dec) (((dec)->intg ? (dec)->intg : 1) + \ + (dec)->frac + ((dec)->frac > 0) + 2) + +/* negate a decimal */ +#define decimal_neg(dec) do { (dec)->sign^=1; } while(0) + +/* + conventions: + + decimal_smth() == 0 -- everything's ok + decimal_smth() <= 1 -- result is usable, but precision loss is possible + decimal_smth() <= 2 -- result can be unusable, most significant digits + could've been lost + decimal_smth() > 2 -- no result was generated +*/ + +#define E_DEC_OK 0 +#define E_DEC_TRUNCATED 1 +#define E_DEC_OVERFLOW 2 +#define E_DEC_DIV_ZERO 4 +#define E_DEC_BAD_NUM 8 +#define E_DEC_OOM 16 + +#define E_DEC_ERROR 31 +#define E_DEC_FATAL_ERROR 30 + +#endif + diff --git a/mysql_incl/errmsg.h b/mysql_incl/errmsg.h new file mode 100644 index 0000000..92d70ab --- /dev/null +++ b/mysql_incl/errmsg.h @@ -0,0 +1,103 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* Error messages for MySQL clients */ +/* (Error messages for the daemon are in sql/share/errmsg.txt) */ + +#ifdef __cplusplus +extern "C" { +#endif +void init_client_errs(void); +void finish_client_errs(void); +extern const char *client_errors[]; /* Error messages */ +#ifdef __cplusplus +} +#endif + +#define CR_MIN_ERROR 2000 /* For easier client code */ +#define CR_MAX_ERROR 2999 +#if !defined(ER) +#define ER(X) client_errors[(X)-CR_MIN_ERROR] +#endif +#define CLIENT_ERRMAP 2 /* Errormap used by my_error() */ + +/* Do not add error numbers before CR_ERROR_FIRST. */ +/* If necessary to add lower numbers, change CR_ERROR_FIRST accordingly. */ +#define CR_ERROR_FIRST 2000 /*Copy first error nr.*/ +#define CR_UNKNOWN_ERROR 2000 +#define CR_SOCKET_CREATE_ERROR 2001 +#define CR_CONNECTION_ERROR 2002 +#define CR_CONN_HOST_ERROR 2003 +#define CR_IPSOCK_ERROR 2004 +#define CR_UNKNOWN_HOST 2005 +#define CR_SERVER_GONE_ERROR 2006 +#define CR_VERSION_ERROR 2007 +#define CR_OUT_OF_MEMORY 2008 +#define CR_WRONG_HOST_INFO 2009 +#define CR_LOCALHOST_CONNECTION 2010 +#define CR_TCP_CONNECTION 2011 +#define CR_SERVER_HANDSHAKE_ERR 2012 +#define CR_SERVER_LOST 2013 +#define CR_COMMANDS_OUT_OF_SYNC 2014 +#define CR_NAMEDPIPE_CONNECTION 2015 +#define CR_NAMEDPIPEWAIT_ERROR 2016 +#define CR_NAMEDPIPEOPEN_ERROR 2017 +#define CR_NAMEDPIPESETSTATE_ERROR 2018 +#define CR_CANT_READ_CHARSET 2019 +#define CR_NET_PACKET_TOO_LARGE 2020 +#define CR_EMBEDDED_CONNECTION 2021 +#define CR_PROBE_SLAVE_STATUS 2022 +#define CR_PROBE_SLAVE_HOSTS 2023 +#define CR_PROBE_SLAVE_CONNECT 2024 +#define CR_PROBE_MASTER_CONNECT 2025 +#define CR_SSL_CONNECTION_ERROR 2026 +#define CR_MALFORMED_PACKET 2027 +#define CR_WRONG_LICENSE 2028 + +/* new 4.1 error codes */ +#define CR_NULL_POINTER 2029 +#define CR_NO_PREPARE_STMT 2030 +#define CR_PARAMS_NOT_BOUND 2031 +#define CR_DATA_TRUNCATED 2032 +#define CR_NO_PARAMETERS_EXISTS 2033 +#define CR_INVALID_PARAMETER_NO 2034 +#define CR_INVALID_BUFFER_USE 2035 +#define CR_UNSUPPORTED_PARAM_TYPE 2036 + +#define CR_SHARED_MEMORY_CONNECTION 2037 +#define CR_SHARED_MEMORY_CONNECT_REQUEST_ERROR 2038 +#define CR_SHARED_MEMORY_CONNECT_ANSWER_ERROR 2039 +#define CR_SHARED_MEMORY_CONNECT_FILE_MAP_ERROR 2040 +#define CR_SHARED_MEMORY_CONNECT_MAP_ERROR 2041 +#define CR_SHARED_MEMORY_FILE_MAP_ERROR 2042 +#define CR_SHARED_MEMORY_MAP_ERROR 2043 +#define CR_SHARED_MEMORY_EVENT_ERROR 2044 +#define CR_SHARED_MEMORY_CONNECT_ABANDONED_ERROR 2045 +#define CR_SHARED_MEMORY_CONNECT_SET_ERROR 2046 +#define CR_CONN_UNKNOW_PROTOCOL 2047 +#define CR_INVALID_CONN_HANDLE 2048 +#define CR_SECURE_AUTH 2049 +#define CR_FETCH_CANCELED 2050 +#define CR_NO_DATA 2051 +#define CR_NO_STMT_METADATA 2052 +#define CR_NO_RESULT_SET 2053 +#define CR_NOT_IMPLEMENTED 2054 +#define CR_SERVER_LOST_EXTENDED 2055 +#define CR_STMT_CLOSED 2056 +#define CR_NEW_STMT_METADATA 2057 +#define CR_ALREADY_CONNECTED 2058 +#define CR_ERROR_LAST /*Copy last error nr:*/ 2058 +/* Add error numbers before CR_ERROR_LAST and change it accordingly. */ + diff --git a/mysql_incl/hash.h b/mysql_incl/hash.h new file mode 100644 index 0000000..c1797c8 --- /dev/null +++ b/mysql_incl/hash.h @@ -0,0 +1,84 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* Dynamic hashing of record with different key-length */ + +#ifndef _hash_h +#define _hash_h +#ifdef __cplusplus +extern "C" { +#endif + +/* + Overhead to store an element in hash + Can be used to approximate memory consumption for a hash + */ +#define HASH_OVERHEAD (sizeof(char*)*2) + +/* flags for hash_init */ +#define HASH_UNIQUE 1 /* hash_insert fails on duplicate key */ + +typedef uchar *(*my_hash_get_key)(const uchar *,size_t*,my_bool); +typedef void (*my_hash_free_key)(void *); +typedef my_bool (*my_hash_walk_action)(void *,void *); + +typedef struct st_hash { + size_t key_offset,key_length; /* Length of key if const length */ + size_t blength; + ulong records; + uint flags; + DYNAMIC_ARRAY array; /* Place for hash_keys */ + my_hash_get_key get_key; + void (*free)(void *); + CHARSET_INFO *charset; +} HASH; + +/* A search iterator state */ +typedef uint HASH_SEARCH_STATE; + +#define my_hash_init(A,B,C,D,E,F,G,H) \ + _my_hash_init(A,0,B,C,D,E,F,G,H CALLER_INFO) +#define my_hash_init2(A,B,C,D,E,F,G,H,I) \ + _my_hash_init(A,B,C,D,E,F,G,H,I CALLER_INFO) +my_bool _my_hash_init(HASH *hash, uint growth_size, CHARSET_INFO *charset, + ulong default_array_elements, size_t key_offset, + size_t key_length, my_hash_get_key get_key, + void (*free_element)(void*), + uint flags CALLER_INFO_PROTO); +void my_hash_free(HASH *tree); +void my_hash_reset(HASH *hash); +uchar *my_hash_element(HASH *hash, ulong idx); +uchar *my_hash_search(const HASH *info, const uchar *key, size_t length); +uchar *my_hash_first(const HASH *info, const uchar *key, size_t length, + HASH_SEARCH_STATE *state); +uchar *my_hash_next(const HASH *info, const uchar *key, size_t length, + HASH_SEARCH_STATE *state); +my_bool my_hash_insert(HASH *info, const uchar *data); +my_bool my_hash_delete(HASH *hash, uchar *record); +my_bool my_hash_update(HASH *hash, uchar *record, uchar *old_key, + size_t old_key_length); +void my_hash_replace(HASH *hash, HASH_SEARCH_STATE *state, uchar *new_row); +my_bool my_hash_check(HASH *hash); /* Only in debug library */ +my_bool my_hash_iterate(HASH *hash, my_hash_walk_action action, void *argument); + +#define my_hash_clear(H) bzero((char*) (H), sizeof(*(H))) +#define my_hash_inited(H) ((H)->array.buffer != 0) +#define my_hash_init_opt(A,B,C,D,E,F,G,H) \ + (!my_hash_inited(A) && _my_hash_init(A,0,B,C,D,E,F,G, H CALLER_INFO)) + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/keycache.h b/mysql_incl/keycache.h new file mode 100644 index 0000000..0375d10 --- /dev/null +++ b/mysql_incl/keycache.h @@ -0,0 +1,153 @@ +/* Copyright (C) 2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/** + @file + Key cache API +*/ + +#ifndef _keycache_h +#define _keycache_h +C_MODE_START + +/* declare structures that is used by st_key_cache */ + +struct st_block_link; +typedef struct st_block_link BLOCK_LINK; +struct st_keycache_page; +typedef struct st_keycache_page KEYCACHE_PAGE; +struct st_hash_link; +typedef struct st_hash_link HASH_LINK; + +/* info about requests in a waiting queue */ +typedef struct st_keycache_wqueue +{ + struct st_my_thread_var *last_thread; /* circular list of waiting threads */ +} KEYCACHE_WQUEUE; + +/** Callback called when any block is flushed */ +typedef int (*KEYCACHE_POST_WRITE_CALLBACK)(void *arg, const uchar *buffert, + uint length, my_off_t filepos); + +#define CHANGED_BLOCKS_HASH 128 /* must be power of 2 */ + +/* + The key cache structure + It also contains read-only statistics parameters. +*/ + +typedef struct st_key_cache +{ + my_bool key_cache_inited; + my_bool in_resize; /* true during resize operation */ + my_bool resize_in_flush; /* true during flush of resize operation */ + my_bool can_be_used; /* usage of cache for read/write is allowed */ + size_t key_cache_mem_size; /* specified size of the cache memory */ + uint key_cache_block_size; /* size of the page buffer of a cache block */ + ulong min_warm_blocks; /* min number of warm blocks; */ + ulong age_threshold; /* age threshold for hot blocks */ + ulonglong keycache_time; /* total number of block link operations */ + uint hash_entries; /* max number of entries in the hash table */ + int hash_links; /* max number of hash links */ + int hash_links_used; /* number of hash links currently used */ + int disk_blocks; /* max number of blocks in the cache */ + ulong blocks_used; /* maximum number of concurrently used blocks */ + ulong blocks_unused; /* number of currently unused blocks */ + ulong blocks_changed; /* number of currently dirty blocks */ + ulong warm_blocks; /* number of blocks in warm sub-chain */ + ulong cnt_for_resize_op; /* counter to block resize operation */ + long blocks_available; /* number of blocks available in the LRU chain */ + HASH_LINK **hash_root; /* arr. of entries into hash table buckets */ + HASH_LINK *hash_link_root; /* memory for hash table links */ + HASH_LINK *free_hash_list; /* list of free hash links */ + BLOCK_LINK *free_block_list; /* list of free blocks */ + BLOCK_LINK *block_root; /* memory for block links */ + uchar HUGE_PTR *block_mem; /* memory for block buffers */ + BLOCK_LINK *used_last; /* ptr to the last block of the LRU chain */ + BLOCK_LINK *used_ins; /* ptr to the insertion block in LRU chain */ + pthread_mutex_t cache_lock; /* to lock access to the cache structure */ + KEYCACHE_WQUEUE resize_queue; /* threads waiting during resize operation */ + /* + Waiting for a zero resize count. Using a queue for symmetry though + only one thread can wait here. + */ + KEYCACHE_WQUEUE waiting_for_resize_cnt; + KEYCACHE_WQUEUE waiting_for_hash_link; /* waiting for a free hash link */ + KEYCACHE_WQUEUE waiting_for_block; /* requests waiting for a free block */ + BLOCK_LINK *changed_blocks[CHANGED_BLOCKS_HASH]; /* hash for dirty file bl.*/ + BLOCK_LINK *file_blocks[CHANGED_BLOCKS_HASH]; /* hash for other file bl.*/ + KEYCACHE_POST_WRITE_CALLBACK post_write;/**< Called when flushing any block*/ + + /* + The following variables are and variables used to hold parameters for + initializing the key cache. + */ + + ulonglong param_buff_size; /* size the memory allocated for the cache */ + ulong param_block_size; /* size of the blocks in the key cache */ + ulong param_division_limit; /* min. percentage of warm blocks */ + ulong param_age_threshold; /* determines when hot block is downgraded */ + + /* Statistics variables. These are reset in reset_key_cache_counters(). */ + ulong global_blocks_changed; /* number of currently dirty blocks */ + ulonglong global_cache_w_requests;/* number of write requests (write hits) */ + ulonglong global_cache_write; /* number of writes from cache to files */ + ulonglong global_cache_r_requests;/* number of read requests (read hits) */ + ulonglong global_cache_read; /* number of reads from files to cache */ + + int blocks; /* max number of blocks in the cache */ + my_bool in_init; /* Set to 1 in MySQL during init/resize */ +} KEY_CACHE; + +/* The default key cache */ +extern KEY_CACHE dflt_key_cache_var, *dflt_key_cache; + +extern int init_key_cache(KEY_CACHE *keycache, uint key_cache_block_size, + size_t use_mem, uint division_limit, + uint age_threshold); +extern int resize_key_cache(KEY_CACHE *keycache, uint key_cache_block_size, + size_t use_mem, uint division_limit, + uint age_threshold); +extern void change_key_cache_param(KEY_CACHE *keycache, uint division_limit, + uint age_threshold); +extern uchar *key_cache_read(KEY_CACHE *keycache, + File file, my_off_t filepos, int level, + uchar *buff, uint length, + uint block_length,int return_buffer); +extern int key_cache_insert(KEY_CACHE *keycache, + File file, my_off_t filepos, int level, + uchar *buff, uint length); +extern int key_cache_write(KEY_CACHE *keycache, + File file, my_off_t filepos, int level, + uchar *buff, uint length, + uint block_length, int force_write, + void *post_write_arg); +extern int flush_key_blocks(KEY_CACHE *keycache, + int file, enum flush_type type); +extern void end_key_cache(KEY_CACHE *keycache, my_bool cleanup); + +/* Functions to handle multiple key caches */ +extern my_bool multi_keycache_init(void); +extern void multi_keycache_free(void); +extern KEY_CACHE *multi_key_cache_search(uchar *key, uint length, + KEY_CACHE *def); +extern my_bool multi_key_cache_set(const uchar *key, uint length, + KEY_CACHE *key_cache); +extern void multi_key_cache_change(KEY_CACHE *old_data, + KEY_CACHE *new_data); +extern int reset_key_cache_counters(const char *name, + KEY_CACHE *key_cache); +C_MODE_END +#endif /* _keycache_h */ diff --git a/mysql_incl/lf.h b/mysql_incl/lf.h new file mode 100644 index 0000000..83358aa --- /dev/null +++ b/mysql_incl/lf.h @@ -0,0 +1,260 @@ +/* Copyright (C) 2007-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _lf_h +#define _lf_h + +#include + +/* + Helpers to define both func() and _func(), where + func() is a _func() protected by my_atomic_rwlock_wrlock() +*/ + +#define lock_wrap(f, t, proto_args, args, lock) \ +t _ ## f proto_args; \ +static inline t f proto_args \ +{ \ + t ret; \ + my_atomic_rwlock_wrlock(lock); \ + ret= _ ## f args; \ + my_atomic_rwlock_wrunlock(lock); \ + return ret; \ +} + +#define lock_wrap_void(f, proto_args, args, lock) \ +void _ ## f proto_args; \ +static inline void f proto_args \ +{ \ + my_atomic_rwlock_wrlock(lock); \ + _ ## f args; \ + my_atomic_rwlock_wrunlock(lock); \ +} + +#define nolock_wrap(f, t, proto_args, args) \ +t _ ## f proto_args; \ +static inline t f proto_args \ +{ \ + return _ ## f args; \ +} + +#define nolock_wrap_void(f, proto_args, args) \ +void _ ## f proto_args; \ +static inline void f proto_args \ +{ \ + _ ## f args; \ +} + +/* + wait-free dynamic array, see lf_dynarray.c + + 4 levels of 256 elements each mean 4311810304 elements in an array - it + should be enough for a while +*/ +#define LF_DYNARRAY_LEVEL_LENGTH 256 +#define LF_DYNARRAY_LEVELS 4 + +typedef struct { + void * volatile level[LF_DYNARRAY_LEVELS]; + uint size_of_element; + my_atomic_rwlock_t lock; +} LF_DYNARRAY; + +typedef int (*lf_dynarray_func)(void *, void *); + +void lf_dynarray_init(LF_DYNARRAY *array, uint element_size); +void lf_dynarray_destroy(LF_DYNARRAY *array); + +nolock_wrap(lf_dynarray_value, void *, + (LF_DYNARRAY *array, uint idx), + (array, idx)) +lock_wrap(lf_dynarray_lvalue, void *, + (LF_DYNARRAY *array, uint idx), + (array, idx), + &array->lock) +nolock_wrap(lf_dynarray_iterate, int, + (LF_DYNARRAY *array, lf_dynarray_func func, void *arg), + (array, func, arg)) + +/* + pin manager for memory allocator, lf_alloc-pin.c +*/ + +#define LF_PINBOX_PINS 4 +#define LF_PURGATORY_SIZE 10 + +typedef void lf_pinbox_free_func(void *, void *, void*); + +typedef struct { + LF_DYNARRAY pinarray; + lf_pinbox_free_func *free_func; + void *free_func_arg; + uint free_ptr_offset; + uint32 volatile pinstack_top_ver; /* this is a versioned pointer */ + uint32 volatile pins_in_array; /* number of elements in array */ +} LF_PINBOX; + +typedef struct { + void * volatile pin[LF_PINBOX_PINS]; + LF_PINBOX *pinbox; + void **stack_ends_here; + void *purgatory; + uint32 purgatory_count; + uint32 volatile link; +/* we want sizeof(LF_PINS) to be 64 to avoid false sharing */ +#if SIZEOF_INT*2+SIZEOF_CHARP*(LF_PINBOX_PINS+3) != 64 + char pad[64-sizeof(uint32)*2-sizeof(void*)*(LF_PINBOX_PINS+3)]; +#endif +} LF_PINS; + +/* + shortcut macros to do an atomic_wrlock on a structure that uses pins + (e.g. lf_hash). +*/ +#define lf_rwlock_by_pins(PINS) \ + my_atomic_rwlock_wrlock(&(PINS)->pinbox->pinarray.lock) +#define lf_rwunlock_by_pins(PINS) \ + my_atomic_rwlock_wrunlock(&(PINS)->pinbox->pinarray.lock) + +/* + compile-time assert, to require "no less than N" pins + it's enough if it'll fail on at least one compiler, so + we'll enable it on GCC only, which supports zero-length arrays. +*/ +#if defined(__GNUC__) && defined(MY_LF_EXTRA_DEBUG) +#define LF_REQUIRE_PINS(N) \ + static const char require_pins[LF_PINBOX_PINS-N] \ + __attribute__ ((unused)); \ + static const int LF_NUM_PINS_IN_THIS_FILE= N; +#define _lf_pin(PINS, PIN, ADDR) \ + ( \ + assert(PIN < LF_NUM_PINS_IN_THIS_FILE), \ + my_atomic_storeptr(&(PINS)->pin[PIN], (ADDR)) \ + ) +#else +#define LF_REQUIRE_PINS(N) +#define _lf_pin(PINS, PIN, ADDR) my_atomic_storeptr(&(PINS)->pin[PIN], (ADDR)) +#endif + +#define _lf_unpin(PINS, PIN) _lf_pin(PINS, PIN, NULL) +#define lf_pin(PINS, PIN, ADDR) \ + do { \ + lf_rwlock_by_pins(PINS); \ + _lf_pin(PINS, PIN, ADDR); \ + lf_rwunlock_by_pins(PINS); \ + } while (0) +#define lf_unpin(PINS, PIN) lf_pin(PINS, PIN, NULL) +#define _lf_assert_pin(PINS, PIN) assert((PINS)->pin[PIN] != 0) +#define _lf_assert_unpin(PINS, PIN) assert((PINS)->pin[PIN] == 0) + +void lf_pinbox_init(LF_PINBOX *pinbox, uint free_ptr_offset, + lf_pinbox_free_func *free_func, void * free_func_arg); +void lf_pinbox_destroy(LF_PINBOX *pinbox); + +lock_wrap(lf_pinbox_get_pins, LF_PINS *, + (LF_PINBOX *pinbox), + (pinbox), + &pinbox->pinarray.lock) +lock_wrap_void(lf_pinbox_put_pins, + (LF_PINS *pins), + (pins), + &pins->pinbox->pinarray.lock) +lock_wrap_void(lf_pinbox_free, + (LF_PINS *pins, void *addr), + (pins, addr), + &pins->pinbox->pinarray.lock) + +/* + memory allocator, lf_alloc-pin.c +*/ + +typedef struct st_lf_allocator { + LF_PINBOX pinbox; + uchar * volatile top; + uint element_size; + uint32 volatile mallocs; + void (*constructor)(uchar *); /* called, when an object is malloc()'ed */ + void (*destructor)(uchar *); /* called, when an object is free()'d */ +} LF_ALLOCATOR; + +void lf_alloc_init(LF_ALLOCATOR *allocator, uint size, uint free_ptr_offset); +void lf_alloc_destroy(LF_ALLOCATOR *allocator); +uint lf_alloc_pool_count(LF_ALLOCATOR *allocator); +/* + shortcut macros to access underlying pinbox functions from an LF_ALLOCATOR + see _lf_pinbox_get_pins() and _lf_pinbox_put_pins() +*/ +#define _lf_alloc_free(PINS, PTR) _lf_pinbox_free((PINS), (PTR)) +#define lf_alloc_free(PINS, PTR) lf_pinbox_free((PINS), (PTR)) +#define _lf_alloc_get_pins(A) _lf_pinbox_get_pins(&(A)->pinbox) +#define lf_alloc_get_pins(A) lf_pinbox_get_pins(&(A)->pinbox) +#define _lf_alloc_put_pins(PINS) _lf_pinbox_put_pins(PINS) +#define lf_alloc_put_pins(PINS) lf_pinbox_put_pins(PINS) +#define lf_alloc_direct_free(ALLOC, ADDR) my_free((uchar*)(ADDR), MYF(0)) + +lock_wrap(lf_alloc_new, void *, + (LF_PINS *pins), + (pins), + &pins->pinbox->pinarray.lock) + +/* + extendible hash, lf_hash.c +*/ +#include + +#define LF_HASH_UNIQUE 1 + +/* lf_hash overhead per element (that is, sizeof(LF_SLIST) */ +extern const int LF_HASH_OVERHEAD; + +typedef struct { + LF_DYNARRAY array; /* hash itself */ + LF_ALLOCATOR alloc; /* allocator for elements */ + my_hash_get_key get_key; /* see HASH */ + CHARSET_INFO *charset; /* see HASH */ + uint key_offset, key_length; /* see HASH */ + uint element_size; /* size of memcpy'ed area on insert */ + uint flags; /* LF_HASH_UNIQUE, etc */ + int32 volatile size; /* size of array */ + int32 volatile count; /* number of elements in the hash */ +} LF_HASH; + +void lf_hash_init(LF_HASH *hash, uint element_size, uint flags, + uint key_offset, uint key_length, my_hash_get_key get_key, + CHARSET_INFO *charset); +void lf_hash_destroy(LF_HASH *hash); +int lf_hash_insert(LF_HASH *hash, LF_PINS *pins, const void *data); +void *lf_hash_search(LF_HASH *hash, LF_PINS *pins, const void *key, uint keylen); +int lf_hash_delete(LF_HASH *hash, LF_PINS *pins, const void *key, uint keylen); +/* + shortcut macros to access underlying pinbox functions from an LF_HASH + see _lf_pinbox_get_pins() and _lf_pinbox_put_pins() +*/ +#define _lf_hash_get_pins(HASH) _lf_alloc_get_pins(&(HASH)->alloc) +#define lf_hash_get_pins(HASH) lf_alloc_get_pins(&(HASH)->alloc) +#define _lf_hash_put_pins(PINS) _lf_pinbox_put_pins(PINS) +#define lf_hash_put_pins(PINS) lf_pinbox_put_pins(PINS) +#define lf_hash_search_unpin(PINS) lf_unpin((PINS), 2) +/* + cleanup +*/ + +#undef lock_wrap_void +#undef lock_wrap +#undef nolock_wrap_void +#undef nolock_wrap + +#endif + diff --git a/mysql_incl/m_ctype.h b/mysql_incl/m_ctype.h new file mode 100644 index 0000000..33229a3 --- /dev/null +++ b/mysql_incl/m_ctype.h @@ -0,0 +1,654 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + A better inplementation of the UNIX ctype(3) library. + Notes: my_global.h should be included before ctype.h +*/ + +#ifndef _m_ctype_h +#define _m_ctype_h + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define MY_CS_NAME_SIZE 32 +#define MY_CS_CTYPE_TABLE_SIZE 257 +#define MY_CS_TO_LOWER_TABLE_SIZE 256 +#define MY_CS_TO_UPPER_TABLE_SIZE 256 +#define MY_CS_SORT_ORDER_TABLE_SIZE 256 +#define MY_CS_TO_UNI_TABLE_SIZE 256 + +#define CHARSET_DIR "charsets/" + +#define my_wc_t ulong + +typedef struct unicase_info_st +{ + uint16 toupper; + uint16 tolower; + uint16 sort; +} MY_UNICASE_INFO; + + +extern MY_UNICASE_INFO *my_unicase_default[256]; +extern MY_UNICASE_INFO *my_unicase_turkish[256]; + +typedef struct uni_ctype_st +{ + uchar pctype; + uchar *ctype; +} MY_UNI_CTYPE; + +extern MY_UNI_CTYPE my_uni_ctype[256]; + +/* wm_wc and wc_mb return codes */ +#define MY_CS_ILSEQ 0 /* Wrong by sequence: wb_wc */ +#define MY_CS_ILUNI 0 /* Cannot encode Unicode to charset: wc_mb */ +#define MY_CS_TOOSMALL -101 /* Need at least one byte: wc_mb and mb_wc */ +#define MY_CS_TOOSMALL2 -102 /* Need at least two bytes: wc_mb and mb_wc */ +#define MY_CS_TOOSMALL3 -103 /* Need at least three bytes: wc_mb and mb_wc */ +/* These following three are currently not really used */ +#define MY_CS_TOOSMALL4 -104 /* Need at least 4 bytes: wc_mb and mb_wc */ +#define MY_CS_TOOSMALL5 -105 /* Need at least 5 bytes: wc_mb and mb_wc */ +#define MY_CS_TOOSMALL6 -106 /* Need at least 6 bytes: wc_mb and mb_wc */ +/* A helper macros for "need at least n bytes" */ +#define MY_CS_TOOSMALLN(n) (-100-(n)) + +#define MY_SEQ_INTTAIL 1 +#define MY_SEQ_SPACES 2 + + /* My charsets_list flags */ +#define MY_CS_COMPILED 1 /* compiled-in sets */ +#define MY_CS_CONFIG 2 /* sets that have a *.conf file */ +#define MY_CS_INDEX 4 /* sets listed in the Index file */ +#define MY_CS_LOADED 8 /* sets that are currently loaded */ +#define MY_CS_BINSORT 16 /* if binary sort order */ +#define MY_CS_PRIMARY 32 /* if primary collation */ +#define MY_CS_STRNXFRM 64 /* if strnxfrm is used for sort */ +#define MY_CS_UNICODE 128 /* is a charset is full unicode */ +#define MY_CS_READY 256 /* if a charset is initialized */ +#define MY_CS_AVAILABLE 512 /* If either compiled-in or loaded*/ +#define MY_CS_CSSORT 1024 /* if case sensitive sort order */ +#define MY_CS_HIDDEN 2048 /* don't display in SHOW */ +#define MY_CS_PUREASCII 4096 /* if a charset is pure ascii */ +#define MY_CS_NONASCII 8192 /* if not ASCII-compatible */ +#define MY_CHARSET_UNDEFINED 0 + +/* Character repertoire flags */ +#define MY_REPERTOIRE_ASCII 1 /* Pure ASCII U+0000..U+007F */ +#define MY_REPERTOIRE_EXTENDED 2 /* Extended characters: U+0080..U+FFFF */ +#define MY_REPERTOIRE_UNICODE30 3 /* ASCII | EXTENDED: U+0000..U+FFFF */ + +/* Flags for strxfrm */ +#define MY_STRXFRM_LEVEL1 0x00000001 /* for primary weights */ +#define MY_STRXFRM_LEVEL2 0x00000002 /* for secondary weights */ +#define MY_STRXFRM_LEVEL3 0x00000004 /* for tertiary weights */ +#define MY_STRXFRM_LEVEL4 0x00000008 /* fourth level weights */ +#define MY_STRXFRM_LEVEL5 0x00000010 /* fifth level weights */ +#define MY_STRXFRM_LEVEL6 0x00000020 /* sixth level weights */ +#define MY_STRXFRM_LEVEL_ALL 0x0000003F /* Bit OR for the above six */ +#define MY_STRXFRM_NLEVELS 6 /* Number of possible levels*/ + +#define MY_STRXFRM_PAD_WITH_SPACE 0x00000040 /* if pad result with spaces */ +#define MY_STRXFRM_PAD_TO_MAXLEN 0x00000080 /* if pad tail(for filesort) */ + +#define MY_STRXFRM_DESC_LEVEL1 0x00000100 /* if desc order for level1 */ +#define MY_STRXFRM_DESC_LEVEL2 0x00000200 /* if desc order for level2 */ +#define MY_STRXFRM_DESC_LEVEL3 0x00000300 /* if desc order for level3 */ +#define MY_STRXFRM_DESC_LEVEL4 0x00000800 /* if desc order for level4 */ +#define MY_STRXFRM_DESC_LEVEL5 0x00001000 /* if desc order for level5 */ +#define MY_STRXFRM_DESC_LEVEL6 0x00002000 /* if desc order for level6 */ +#define MY_STRXFRM_DESC_SHIFT 8 + +#define MY_STRXFRM_UNUSED_00004000 0x00004000 /* for future extensions */ +#define MY_STRXFRM_UNUSED_00008000 0x00008000 /* for future extensions */ + +#define MY_STRXFRM_REVERSE_LEVEL1 0x00010000 /* if reverse order for level1 */ +#define MY_STRXFRM_REVERSE_LEVEL2 0x00020000 /* if reverse order for level2 */ +#define MY_STRXFRM_REVERSE_LEVEL3 0x00040000 /* if reverse order for level3 */ +#define MY_STRXFRM_REVERSE_LEVEL4 0x00080000 /* if reverse order for level4 */ +#define MY_STRXFRM_REVERSE_LEVEL5 0x00100000 /* if reverse order for level5 */ +#define MY_STRXFRM_REVERSE_LEVEL6 0x00200000 /* if reverse order for level6 */ +#define MY_STRXFRM_REVERSE_SHIFT 16 + + +typedef struct my_uni_idx_st +{ + uint16 from; + uint16 to; + uchar *tab; +} MY_UNI_IDX; + +typedef struct +{ + uint beg; + uint end; + uint mb_len; +} my_match_t; + +enum my_lex_states +{ + MY_LEX_START, MY_LEX_CHAR, MY_LEX_IDENT, + MY_LEX_IDENT_SEP, MY_LEX_IDENT_START, + MY_LEX_REAL, MY_LEX_HEX_NUMBER, MY_LEX_BIN_NUMBER, + MY_LEX_CMP_OP, MY_LEX_LONG_CMP_OP, MY_LEX_STRING, MY_LEX_COMMENT, MY_LEX_END, + MY_LEX_OPERATOR_OR_IDENT, MY_LEX_NUMBER_IDENT, MY_LEX_INT_OR_REAL, + MY_LEX_REAL_OR_POINT, MY_LEX_BOOL, MY_LEX_EOL, MY_LEX_ESCAPE, + MY_LEX_LONG_COMMENT, MY_LEX_END_LONG_COMMENT, MY_LEX_SEMICOLON, + MY_LEX_SET_VAR, MY_LEX_USER_END, MY_LEX_HOSTNAME, MY_LEX_SKIP, + MY_LEX_USER_VARIABLE_DELIMITER, MY_LEX_SYSTEM_VAR, + MY_LEX_IDENT_OR_KEYWORD, + MY_LEX_IDENT_OR_HEX, MY_LEX_IDENT_OR_BIN, MY_LEX_IDENT_OR_NCHAR, + MY_LEX_STRING_OR_DELIMITER +}; + +struct charset_info_st; + + +/* See strings/CHARSET_INFO.txt for information about this structure */ +typedef struct my_collation_handler_st +{ + my_bool (*init)(struct charset_info_st *, void *(*alloc)(size_t)); + /* Collation routines */ + int (*strnncoll)(struct charset_info_st *, + const uchar *, size_t, const uchar *, size_t, my_bool); + int (*strnncollsp)(struct charset_info_st *, + const uchar *, size_t, const uchar *, size_t, + my_bool diff_if_only_endspace_difference); + size_t (*strnxfrm)(struct charset_info_st *, + uchar *dst, size_t dstlen, uint nweights, + const uchar *src, size_t srclen, uint flags); + size_t (*strnxfrmlen)(struct charset_info_st *, size_t); + my_bool (*like_range)(struct charset_info_st *, + const char *s, size_t s_length, + pchar w_prefix, pchar w_one, pchar w_many, + size_t res_length, + char *min_str, char *max_str, + size_t *min_len, size_t *max_len); + int (*wildcmp)(struct charset_info_st *, + const char *str,const char *str_end, + const char *wildstr,const char *wildend, + int escape,int w_one, int w_many); + + int (*strcasecmp)(struct charset_info_st *, const char *, const char *); + + uint (*instr)(struct charset_info_st *, + const char *b, size_t b_length, + const char *s, size_t s_length, + my_match_t *match, uint nmatch); + + /* Hash calculation */ + void (*hash_sort)(struct charset_info_st *cs, const uchar *key, size_t len, + ulong *nr1, ulong *nr2); + my_bool (*propagate)(struct charset_info_st *cs, const uchar *str, size_t len); +} MY_COLLATION_HANDLER; + +extern MY_COLLATION_HANDLER my_collation_mb_bin_handler; +extern MY_COLLATION_HANDLER my_collation_8bit_bin_handler; +extern MY_COLLATION_HANDLER my_collation_8bit_simple_ci_handler; +extern MY_COLLATION_HANDLER my_collation_ucs2_uca_handler; + +/* Some typedef to make it easy for C++ to make function pointers */ +typedef int (*my_charset_conv_mb_wc)(struct charset_info_st *, my_wc_t *, + const uchar *, const uchar *); +typedef int (*my_charset_conv_wc_mb)(struct charset_info_st *, my_wc_t, + uchar *, uchar *); +typedef size_t (*my_charset_conv_case)(struct charset_info_st *, + char *, size_t, char *, size_t); + + +/* See strings/CHARSET_INFO.txt about information on this structure */ +typedef struct my_charset_handler_st +{ + my_bool (*init)(struct charset_info_st *, void *(*alloc)(size_t)); + /* Multibyte routines */ + uint (*ismbchar)(struct charset_info_st *, const char *, const char *); + uint (*mbcharlen)(struct charset_info_st *, uint c); + size_t (*numchars)(struct charset_info_st *, const char *b, const char *e); + size_t (*charpos)(struct charset_info_st *, const char *b, const char *e, + size_t pos); + size_t (*well_formed_len)(struct charset_info_st *, + const char *b,const char *e, + size_t nchars, int *error); + size_t (*lengthsp)(struct charset_info_st *, const char *ptr, size_t length); + size_t (*numcells)(struct charset_info_st *, const char *b, const char *e); + + /* Unicode conversion */ + my_charset_conv_mb_wc mb_wc; + my_charset_conv_wc_mb wc_mb; + + /* CTYPE scanner */ + int (*ctype)(struct charset_info_st *cs, int *ctype, + const uchar *s, const uchar *e); + + /* Functions for case and sort conversion */ + size_t (*caseup_str)(struct charset_info_st *, char *); + size_t (*casedn_str)(struct charset_info_st *, char *); + + my_charset_conv_case caseup; + my_charset_conv_case casedn; + + /* Charset dependant snprintf() */ + size_t (*snprintf)(struct charset_info_st *, char *to, size_t n, + const char *fmt, + ...) ATTRIBUTE_FORMAT_FPTR(printf, 4, 5); + size_t (*long10_to_str)(struct charset_info_st *, char *to, size_t n, + int radix, long int val); + size_t (*longlong10_to_str)(struct charset_info_st *, char *to, size_t n, + int radix, longlong val); + + void (*fill)(struct charset_info_st *, char *to, size_t len, int fill); + + /* String-to-number conversion routines */ + long (*strntol)(struct charset_info_st *, const char *s, size_t l, + int base, char **e, int *err); + ulong (*strntoul)(struct charset_info_st *, const char *s, size_t l, + int base, char **e, int *err); + longlong (*strntoll)(struct charset_info_st *, const char *s, size_t l, + int base, char **e, int *err); + ulonglong (*strntoull)(struct charset_info_st *, const char *s, size_t l, + int base, char **e, int *err); + double (*strntod)(struct charset_info_st *, char *s, size_t l, char **e, + int *err); + longlong (*strtoll10)(struct charset_info_st *cs, + const char *nptr, char **endptr, int *error); + ulonglong (*strntoull10rnd)(struct charset_info_st *cs, + const char *str, size_t length, + int unsigned_fl, + char **endptr, int *error); + size_t (*scan)(struct charset_info_st *, const char *b, const char *e, + int sq); +} MY_CHARSET_HANDLER; + +extern MY_CHARSET_HANDLER my_charset_8bit_handler; +extern MY_CHARSET_HANDLER my_charset_ucs2_handler; + + +/* See strings/CHARSET_INFO.txt about information on this structure */ +typedef struct charset_info_st +{ + uint number; + uint primary_number; + uint binary_number; + uint state; + const char *csname; + const char *name; + const char *comment; + const char *tailoring; + uchar *ctype; + uchar *to_lower; + uchar *to_upper; + uchar *sort_order; + uint16 *contractions; + uint16 **sort_order_big; + uint16 *tab_to_uni; + MY_UNI_IDX *tab_from_uni; + MY_UNICASE_INFO **caseinfo; + uchar *state_map; + uchar *ident_map; + uint strxfrm_multiply; + uchar caseup_multiply; + uchar casedn_multiply; + uint mbminlen; + uint mbmaxlen; + uint16 min_sort_char; + uint16 max_sort_char; /* For LIKE optimization */ + uchar pad_char; + my_bool escape_with_backslash_is_dangerous; + uchar levels_for_compare; + uchar levels_for_order; + + MY_CHARSET_HANDLER *cset; + MY_COLLATION_HANDLER *coll; + +} CHARSET_INFO; +#define ILLEGAL_CHARSET_INFO_NUMBER (~0U) + + +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO my_charset_bin; +extern CHARSET_INFO my_charset_big5_chinese_ci; +extern CHARSET_INFO my_charset_big5_bin; +extern CHARSET_INFO my_charset_cp932_japanese_ci; +extern CHARSET_INFO my_charset_cp932_bin; +extern CHARSET_INFO my_charset_cp1250_czech_ci; +extern CHARSET_INFO my_charset_eucjpms_japanese_ci; +extern CHARSET_INFO my_charset_eucjpms_bin; +extern CHARSET_INFO my_charset_euckr_korean_ci; +extern CHARSET_INFO my_charset_euckr_bin; +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO my_charset_filename; +extern CHARSET_INFO my_charset_gb2312_chinese_ci; +extern CHARSET_INFO my_charset_gb2312_bin; +extern CHARSET_INFO my_charset_gbk_chinese_ci; +extern CHARSET_INFO my_charset_gbk_bin; +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO my_charset_latin1; +extern CHARSET_INFO my_charset_latin1_german2_ci; +extern CHARSET_INFO my_charset_latin1_bin; +extern CHARSET_INFO my_charset_latin2_czech_ci; +extern CHARSET_INFO my_charset_sjis_japanese_ci; +extern CHARSET_INFO my_charset_sjis_bin; +extern CHARSET_INFO my_charset_tis620_thai_ci; +extern CHARSET_INFO my_charset_tis620_bin; +extern CHARSET_INFO my_charset_ucs2_general_ci; +extern CHARSET_INFO my_charset_ucs2_bin; +extern CHARSET_INFO my_charset_ucs2_unicode_ci; +extern CHARSET_INFO my_charset_ujis_japanese_ci; +extern CHARSET_INFO my_charset_ujis_bin; +extern CHARSET_INFO my_charset_utf16_bin; +extern CHARSET_INFO my_charset_utf16_general_ci; +extern CHARSET_INFO my_charset_utf16_unicode_ci; +extern CHARSET_INFO my_charset_utf32_bin; +extern CHARSET_INFO my_charset_utf32_general_ci; +extern CHARSET_INFO my_charset_utf32_unicode_ci; +extern CHARSET_INFO my_charset_utf8mb3_bin; +extern CHARSET_INFO my_charset_utf8mb3_general_ci; +extern CHARSET_INFO my_charset_utf8mb3_unicode_ci; +extern CHARSET_INFO my_charset_utf8mb4_bin; +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO my_charset_utf8mb4_general_ci; +extern CHARSET_INFO my_charset_utf8mb4_unicode_ci; + +#define MY_UTF8MB3 "utf8mb3" +#define MY_UTF8MB4 "utf8" +#define my_charset_utf8_general_ci my_charset_utf8mb4_general_ci +#define my_charset_utf8_bin my_charset_utf8mb4_bin + + +/* declarations for simple charsets */ +extern size_t my_strnxfrm_simple(CHARSET_INFO *, + uchar *dst, size_t dstlen, uint nweights, + const uchar *src, size_t srclen, uint flags); +size_t my_strnxfrmlen_simple(CHARSET_INFO *, size_t); +extern int my_strnncoll_simple(CHARSET_INFO *, const uchar *, size_t, + const uchar *, size_t, my_bool); + +extern int my_strnncollsp_simple(CHARSET_INFO *, const uchar *, size_t, + const uchar *, size_t, + my_bool diff_if_only_endspace_difference); + +extern void my_hash_sort_simple(CHARSET_INFO *cs, + const uchar *key, size_t len, + ulong *nr1, ulong *nr2); + +extern size_t my_lengthsp_8bit(CHARSET_INFO *cs, const char *ptr, size_t length); + +extern uint my_instr_simple(struct charset_info_st *, + const char *b, size_t b_length, + const char *s, size_t s_length, + my_match_t *match, uint nmatch); + + +/* Functions for 8bit */ +extern size_t my_caseup_str_8bit(CHARSET_INFO *, char *); +extern size_t my_casedn_str_8bit(CHARSET_INFO *, char *); +extern size_t my_caseup_8bit(CHARSET_INFO *, char *src, size_t srclen, + char *dst, size_t dstlen); +extern size_t my_casedn_8bit(CHARSET_INFO *, char *src, size_t srclen, + char *dst, size_t dstlen); + +extern int my_strcasecmp_8bit(CHARSET_INFO * cs, const char *, const char *); + +int my_mb_wc_8bit(CHARSET_INFO *cs,my_wc_t *wc, const uchar *s,const uchar *e); +int my_wc_mb_8bit(CHARSET_INFO *cs,my_wc_t wc, uchar *s, uchar *e); + +int my_mb_ctype_8bit(CHARSET_INFO *,int *, const uchar *,const uchar *); +int my_mb_ctype_mb(CHARSET_INFO *,int *, const uchar *,const uchar *); + +size_t my_scan_8bit(CHARSET_INFO *cs, const char *b, const char *e, int sq); + +size_t my_snprintf_8bit(struct charset_info_st *, char *to, size_t n, + const char *fmt, ...) + ATTRIBUTE_FORMAT(printf, 4, 5); + +long my_strntol_8bit(CHARSET_INFO *, const char *s, size_t l, int base, + char **e, int *err); +ulong my_strntoul_8bit(CHARSET_INFO *, const char *s, size_t l, int base, + char **e, int *err); +longlong my_strntoll_8bit(CHARSET_INFO *, const char *s, size_t l, int base, + char **e, int *err); +ulonglong my_strntoull_8bit(CHARSET_INFO *, const char *s, size_t l, int base, + char **e, int *err); +double my_strntod_8bit(CHARSET_INFO *, char *s, size_t l,char **e, + int *err); +size_t my_long10_to_str_8bit(CHARSET_INFO *, char *to, size_t l, int radix, + long int val); +size_t my_longlong10_to_str_8bit(CHARSET_INFO *, char *to, size_t l, int radix, + longlong val); + +longlong my_strtoll10_8bit(CHARSET_INFO *cs, + const char *nptr, char **endptr, int *error); +longlong my_strtoll10_ucs2(CHARSET_INFO *cs, + const char *nptr, char **endptr, int *error); + +ulonglong my_strntoull10rnd_8bit(CHARSET_INFO *cs, + const char *str, size_t length, int + unsigned_fl, char **endptr, int *error); +ulonglong my_strntoull10rnd_ucs2(CHARSET_INFO *cs, + const char *str, size_t length, + int unsigned_fl, char **endptr, int *error); + +void my_fill_8bit(CHARSET_INFO *cs, char* to, size_t l, int fill); + +my_bool my_like_range_simple(CHARSET_INFO *cs, + const char *ptr, size_t ptr_length, + pbool escape, pbool w_one, pbool w_many, + size_t res_length, + char *min_str, char *max_str, + size_t *min_length, size_t *max_length); + +my_bool my_like_range_mb(CHARSET_INFO *cs, + const char *ptr, size_t ptr_length, + pbool escape, pbool w_one, pbool w_many, + size_t res_length, + char *min_str, char *max_str, + size_t *min_length, size_t *max_length); + +my_bool my_like_range_ucs2(CHARSET_INFO *cs, + const char *ptr, size_t ptr_length, + pbool escape, pbool w_one, pbool w_many, + size_t res_length, + char *min_str, char *max_str, + size_t *min_length, size_t *max_length); + +my_bool my_like_range_utf16(CHARSET_INFO *cs, + const char *ptr, size_t ptr_length, + pbool escape, pbool w_one, pbool w_many, + size_t res_length, + char *min_str, char *max_str, + size_t *min_length, size_t *max_length); + +my_bool my_like_range_utf32(CHARSET_INFO *cs, + const char *ptr, size_t ptr_length, + pbool escape, pbool w_one, pbool w_many, + size_t res_length, + char *min_str, char *max_str, + size_t *min_length, size_t *max_length); + + +int my_wildcmp_8bit(CHARSET_INFO *, + const char *str,const char *str_end, + const char *wildstr,const char *wildend, + int escape, int w_one, int w_many); + +int my_wildcmp_bin(CHARSET_INFO *, + const char *str,const char *str_end, + const char *wildstr,const char *wildend, + int escape, int w_one, int w_many); + +size_t my_numchars_8bit(CHARSET_INFO *, const char *b, const char *e); +size_t my_numcells_8bit(CHARSET_INFO *, const char *b, const char *e); +size_t my_charpos_8bit(CHARSET_INFO *, const char *b, const char *e, size_t pos); +size_t my_well_formed_len_8bit(CHARSET_INFO *, const char *b, const char *e, + size_t pos, int *error); +uint my_mbcharlen_8bit(CHARSET_INFO *, uint c); + + +/* Functions for multibyte charsets */ +extern size_t my_caseup_str_mb(CHARSET_INFO *, char *); +extern size_t my_casedn_str_mb(CHARSET_INFO *, char *); +extern size_t my_caseup_mb(CHARSET_INFO *, char *src, size_t srclen, + char *dst, size_t dstlen); +extern size_t my_casedn_mb(CHARSET_INFO *, char *src, size_t srclen, + char *dst, size_t dstlen); +extern int my_strcasecmp_mb(CHARSET_INFO * cs,const char *, const char *); + +int my_wildcmp_mb(CHARSET_INFO *, + const char *str,const char *str_end, + const char *wildstr,const char *wildend, + int escape, int w_one, int w_many); +size_t my_numchars_mb(CHARSET_INFO *, const char *b, const char *e); +size_t my_numcells_mb(CHARSET_INFO *, const char *b, const char *e); +size_t my_charpos_mb(CHARSET_INFO *, const char *b, const char *e, size_t pos); +size_t my_well_formed_len_mb(CHARSET_INFO *, const char *b, const char *e, + size_t pos, int *error); +uint my_instr_mb(struct charset_info_st *, + const char *b, size_t b_length, + const char *s, size_t s_length, + my_match_t *match, uint nmatch); + +int my_strnncoll_mb_bin(CHARSET_INFO * cs, + const uchar *s, size_t slen, + const uchar *t, size_t tlen, + my_bool t_is_prefix); + +int my_strnncollsp_mb_bin(CHARSET_INFO *cs, + const uchar *a, size_t a_length, + const uchar *b, size_t b_length, + my_bool diff_if_only_endspace_difference); + +int my_wildcmp_mb_bin(CHARSET_INFO *cs, + const char *str,const char *str_end, + const char *wildstr,const char *wildend, + int escape, int w_one, int w_many); + +int my_strcasecmp_mb_bin(CHARSET_INFO * cs __attribute__((unused)), + const char *s, const char *t); + +void my_hash_sort_mb_bin(CHARSET_INFO *cs __attribute__((unused)), + const uchar *key, size_t len,ulong *nr1, ulong *nr2); + +size_t my_strnxfrm_mb(CHARSET_INFO *, + uchar *dst, size_t dstlen, uint nweights, + const uchar *src, size_t srclen, uint flags); + +size_t my_strnxfrm_unicode(CHARSET_INFO *, + uchar *dst, size_t dstlen, uint nweights, + const uchar *src, size_t srclen, uint flags); + +int my_wildcmp_unicode(CHARSET_INFO *cs, + const char *str, const char *str_end, + const char *wildstr, const char *wildend, + int escape, int w_one, int w_many, + MY_UNICASE_INFO **weights); + +extern my_bool my_parse_charset_xml(const char *bug, size_t len, + int (*add)(CHARSET_INFO *cs)); +extern char *my_strchr(CHARSET_INFO *cs, const char *str, const char *end, + pchar c); + +my_bool my_propagate_simple(CHARSET_INFO *cs, const uchar *str, size_t len); +my_bool my_propagate_complex(CHARSET_INFO *cs, const uchar *str, size_t len); + + +uint my_string_repertoire(CHARSET_INFO *cs, const char *str, ulong len); +my_bool my_charset_is_ascii_based(CHARSET_INFO *cs); +my_bool my_charset_is_8bit_pure_ascii(CHARSET_INFO *cs); +uint my_charset_repertoire(CHARSET_INFO *cs); + + +uint my_strxfrm_flag_normalize(uint flags, uint nlevels); +void my_strxfrm_desc_and_reverse(uchar *str, uchar *strend, + uint flags, uint level); +size_t my_strxfrm_pad_desc_and_reverse(CHARSET_INFO *cs, + uchar *str, uchar *frmend, uchar *strend, + uint nweights, uint flags, uint level); + +my_bool my_charset_is_ascii_compatible(CHARSET_INFO *cs); + +#define _MY_U 01 /* Upper case */ +#define _MY_L 02 /* Lower case */ +#define _MY_NMR 04 /* Numeral (digit) */ +#define _MY_SPC 010 /* Spacing character */ +#define _MY_PNT 020 /* Punctuation */ +#define _MY_CTR 040 /* Control character */ +#define _MY_B 0100 /* Blank */ +#define _MY_X 0200 /* heXadecimal digit */ + + +#define my_isascii(c) (!((c) & ~0177)) +#define my_toascii(c) ((c) & 0177) +#define my_tocntrl(c) ((c) & 31) +#define my_toprint(c) ((c) | 64) +#define my_toupper(s,c) (char) ((s)->to_upper[(uchar) (c)]) +#define my_tolower(s,c) (char) ((s)->to_lower[(uchar) (c)]) +#define my_isalpha(s, c) (((s)->ctype+1)[(uchar) (c)] & (_MY_U | _MY_L)) +#define my_isupper(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_U) +#define my_islower(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_L) +#define my_isdigit(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_NMR) +#define my_isxdigit(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_X) +#define my_isalnum(s, c) (((s)->ctype+1)[(uchar) (c)] & (_MY_U | _MY_L | _MY_NMR)) +#define my_isspace(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_SPC) +#define my_ispunct(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_PNT) +#define my_isprint(s, c) (((s)->ctype+1)[(uchar) (c)] & (_MY_PNT | _MY_U | _MY_L | _MY_NMR | _MY_B)) +#define my_isgraph(s, c) (((s)->ctype+1)[(uchar) (c)] & (_MY_PNT | _MY_U | _MY_L | _MY_NMR)) +#define my_iscntrl(s, c) (((s)->ctype+1)[(uchar) (c)] & _MY_CTR) + +/* Some macros that should be cleaned up a little */ +#define my_isvar(s,c) (my_isalnum(s,c) || (c) == '_') +#define my_isvar_start(s,c) (my_isalpha(s,c) || (c) == '_') + +#define my_binary_compare(s) ((s)->state & MY_CS_BINSORT) +#define use_strnxfrm(s) ((s)->state & MY_CS_STRNXFRM) +#define my_strnxfrm(cs, d, dl, s, sl) \ + ((cs)->coll->strnxfrm((cs), (d), (dl), (dl), (s), (sl), MY_STRXFRM_PAD_WITH_SPACE)) +#define my_strnncoll(s, a, b, c, d) ((s)->coll->strnncoll((s), (a), (b), (c), (d), 0)) +#define my_like_range(s, a, b, c, d, e, f, g, h, i, j) \ + ((s)->coll->like_range((s), (a), (b), (c), (d), (e), (f), (g), (h), (i), (j))) +#define my_wildcmp(cs,s,se,w,we,e,o,m) ((cs)->coll->wildcmp((cs),(s),(se),(w),(we),(e),(o),(m))) +#define my_strcasecmp(s, a, b) ((s)->coll->strcasecmp((s), (a), (b))) +#define my_charpos(cs, b, e, num) (cs)->cset->charpos((cs), (const char*) (b), (const char *)(e), (num)) + + +#define use_mb(s) ((s)->cset->ismbchar != NULL) +#define my_ismbchar(s, a, b) ((s)->cset->ismbchar((s), (a), (b))) +#ifdef USE_MB +#define my_mbcharlen(s, a) ((s)->cset->mbcharlen((s),(a))) +#else +#define my_mbcharlen(s, a) 1 +#endif + +#define my_caseup_str(s, a) ((s)->cset->caseup_str((s), (a))) +#define my_casedn_str(s, a) ((s)->cset->casedn_str((s), (a))) +#define my_strntol(s, a, b, c, d, e) ((s)->cset->strntol((s),(a),(b),(c),(d),(e))) +#define my_strntoul(s, a, b, c, d, e) ((s)->cset->strntoul((s),(a),(b),(c),(d),(e))) +#define my_strntoll(s, a, b, c, d, e) ((s)->cset->strntoll((s),(a),(b),(c),(d),(e))) +#define my_strntoull(s, a, b, c,d, e) ((s)->cset->strntoull((s),(a),(b),(c),(d),(e))) +#define my_strntod(s, a, b, c, d) ((s)->cset->strntod((s),(a),(b),(c),(d))) + + +/* XXX: still need to take care of this one */ +#ifdef MY_CHARSET_TIS620 +#error The TIS620 charset is broken at the moment. Tell tim to fix it. +#define USE_TIS620 +#include "t_ctype.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _m_ctype_h */ diff --git a/mysql_incl/m_string.h b/mysql_incl/m_string.h new file mode 100644 index 0000000..bb8bad4 --- /dev/null +++ b/mysql_incl/m_string.h @@ -0,0 +1,393 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* There may be prolems include all of theese. Try to test in + configure with ones are needed? */ + +/* This is needed for the definitions of strchr... on solaris */ + +#ifndef _m_string_h +#define _m_string_h +#ifndef __USE_GNU +#define __USE_GNU /* We want to use stpcpy */ +#endif +#if defined(HAVE_STRINGS_H) +#include +#endif +#if defined(HAVE_STRING_H) +#include +#endif + +/* need by my_vsnprintf */ +#include + +#ifdef _AIX +#undef HAVE_BCMP +#endif + +/* This is needed for the definitions of bzero... on solaris */ +#if defined(HAVE_STRINGS_H) +#include +#endif + +/* This is needed for the definitions of memcpy... on solaris */ +#if defined(HAVE_MEMORY_H) && !defined(__cplusplus) +#include +#endif + +#if !defined(HAVE_MEMCPY) && !defined(HAVE_MEMMOVE) +# define memcpy(d, s, n) bcopy ((s), (d), (n)) +# define memset(A,C,B) bfill((A),(B),(C)) +# define memmove(d, s, n) bmove ((d), (s), (n)) +#elif defined(HAVE_MEMMOVE) +# define bmove(d, s, n) memmove((d), (s), (n)) +#else +# define memmove(d, s, n) bmove((d), (s), (n)) /* our bmove */ +#endif + +/* Unixware 7 */ +#if !defined(HAVE_BFILL) +# define bfill(A,B,C) memset((A),(C),(B)) +# define bmove_align(A,B,C) memcpy((A),(B),(C)) +#endif + +#if !defined(HAVE_BCMP) +# define bcopy(s, d, n) memcpy((d), (s), (n)) +# define bcmp(A,B,C) memcmp((A),(B),(C)) +# define bzero(A,B) memset((A),0,(B)) +# define bmove_align(A,B,C) memcpy((A),(B),(C)) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +/* + my_str_malloc() and my_str_free() are assigned to implementations in + strings/alloc.c, but can be overridden in the calling program. + */ +extern void *(*my_str_malloc)(size_t); +extern void (*my_str_free)(void *); + +#if defined(HAVE_STPCPY) +#define strmov(A,B) stpcpy((A),(B)) +#ifndef stpcpy +extern char *stpcpy(char *, const char *); /* For AIX with gcc 2.95.3 */ +#endif +#endif + +/* Declared in int2str() */ +extern char NEAR _dig_vec_upper[]; +extern char NEAR _dig_vec_lower[]; + +#ifdef BAD_STRING_COMPILER +#define strmov(A,B) (memccpy(A,B,0,INT_MAX)-1) +#else +#define strmov_overlapp(A,B) strmov(A,B) +#define strmake_overlapp(A,B,C) strmake(A,B,C) +#endif + +#ifdef BAD_MEMCPY /* Problem with gcc on Alpha */ +#define memcpy_fixed(A,B,C) bmove((A),(B),(C)) +#else +#define memcpy_fixed(A,B,C) memcpy((A),(B),(C)) +#endif + +#if (!defined(USE_BMOVE512) || defined(HAVE_purify)) && !defined(bmove512) +#define bmove512(A,B,C) memcpy(A,B,C) +#endif + + /* Prototypes for string functions */ + +#if !defined(bfill) && !defined(HAVE_BFILL) +extern void bfill(uchar *dst,size_t len,pchar fill); +#endif + +#if !defined(bzero) && !defined(HAVE_BZERO) +extern void bzero(uchar * dst,size_t len); +#endif + +#if !defined(bcmp) && !defined(HAVE_BCMP) +extern size_t bcmp(const uchar *s1,const uchar *s2,size_t len); +#endif +#ifdef HAVE_purify +extern size_t my_bcmp(const uchar *s1,const uchar *s2,size_t len); +#undef bcmp +#define bcmp(A,B,C) my_bcmp((A),(B),(C)) +#define bzero_if_purify(A,B) bzero(A,B) +#else +#define bzero_if_purify(A,B) +#endif /* HAVE_purify */ + +#if defined(_lint) || defined(FORCE_INIT_OF_VARS) +#define LINT_INIT_STRUCT(var) bzero(&var, sizeof(var)) /* No uninitialize-warning */ +#else +#define LINT_INIT_STRUCT(var) +#endif + +#ifndef bmove512 +extern void bmove512(uchar *dst,const uchar *src,size_t len); +#endif + +#if !defined(HAVE_BMOVE) && !defined(bmove) +extern void bmove(uuchar *dst, const uchar *src,size_t len); +#endif + +extern void bmove_upp(uchar *dst,const uchar *src,size_t len); +extern void bchange(uchar *dst,size_t old_len,const uchar *src, + size_t new_len,size_t tot_len); +extern void strappend(char *s,size_t len,pchar fill); +extern char *strend(const char *s); +extern char *strcend(const char *, pchar); +extern char *strfield(char *src,int fields,int chars,int blanks, + int tabch); +extern char *strfill(char * s,size_t len,pchar fill); +extern size_t strinstr(const char *str,const char *search); +extern size_t r_strinstr(const char *str, size_t from, const char *search); +extern char *strkey(char *dst,char *head,char *tail,char *flags); +extern char *strmake(char *dst,const char *src,size_t length); +#ifndef strmake_overlapp +extern char *strmake_overlapp(char *dst,const char *src, size_t length); +#endif + +#ifndef strmov +extern char *strmov(char *dst,const char *src); +#endif +extern char *strnmov(char *dst,const char *src,size_t n); +extern char *strsuff(const char *src,const char *suffix); +extern char *strcont(const char *src,const char *set); +extern char *strxcat _VARARGS((char *dst,const char *src, ...)); +extern char *strxmov _VARARGS((char *dst,const char *src, ...)); +extern char *strxcpy _VARARGS((char *dst,const char *src, ...)); +extern char *strxncat _VARARGS((char *dst,size_t len, const char *src, ...)); +extern char *strxnmov _VARARGS((char *dst,size_t len, const char *src, ...)); +extern char *strxncpy _VARARGS((char *dst,size_t len, const char *src, ...)); + +/* Prototypes of normal stringfunctions (with may ours) */ + +#ifdef WANT_STRING_PROTOTYPES +extern char *strcat(char *, const char *); +extern char *strchr(const char *, pchar); +extern char *strrchr(const char *, pchar); +extern char *strcpy(char *, const char *); +extern int strcmp(const char *, const char *); +#ifndef __GNUC__ +extern size_t strlen(const char *); +#endif +#endif +#ifndef HAVE_STRNLEN +extern size_t strnlen(const char *s, size_t n); +#endif + +#if !defined(__cplusplus) +#ifndef HAVE_STRPBRK +extern char *strpbrk(const char *, const char *); +#endif +#ifndef HAVE_STRSTR +extern char *strstr(const char *, const char *); +#endif +#endif +extern int is_prefix(const char *, const char *); + +/* Conversion routines */ +typedef enum { + MY_GCVT_ARG_FLOAT, + MY_GCVT_ARG_DOUBLE +} my_gcvt_arg_type; + +double my_strtod(const char *str, char **end, int *error); +double my_atof(const char *nptr); +size_t my_fcvt(double x, int precision, char *to, my_bool *error); +size_t my_gcvt(double x, my_gcvt_arg_type type, int width, char *to, + my_bool *error); + +#define NOT_FIXED_DEC 31 + +/* + The longest string my_fcvt can return is 311 + "precision" bytes. + Here we assume that we never cal my_fcvt() with precision >= NOT_FIXED_DEC + (+ 1 byte for the terminating '\0'). +*/ +#define FLOATING_POINT_BUFFER (311 + NOT_FIXED_DEC) + +/* + We want to use the 'e' format in some cases even if we have enough space + for the 'f' one just to mimic sprintf("%.15g") behavior for large integers, + and to improve it for numbers < 10^(-4). + That is, for |x| < 1 we require |x| >= 10^(-15), and for |x| > 1 we require + it to be integer and be <= 10^DBL_DIG for the 'f' format to be used. + We don't lose precision, but make cases like "1e200" or "0.00001" look nicer. +*/ +#define MAX_DECPT_FOR_F_FORMAT DBL_DIG + +/* + The maximum possible field width for my_gcvt() conversion. + (DBL_DIG + 2) significant digits + sign + "." + ("e-NNN" or + MAX_DECPT_FOR_F_FORMAT zeros for cases when |x|<1 and the 'f' format is used). +*/ +#define MY_GCVT_MAX_FIELD_WIDTH (DBL_DIG + 4 + max(5, MAX_DECPT_FOR_F_FORMAT)) + + +extern char *llstr(longlong value,char *buff); +extern char *ullstr(longlong value,char *buff); +#ifndef HAVE_STRTOUL +extern long strtol(const char *str, char **ptr, int base); +extern ulong strtoul(const char *str, char **ptr, int base); +#endif + +extern char *int2str(long val, char *dst, int radix, int upcase); +extern char *int10_to_str(long val,char *dst,int radix); +extern char *str2int(const char *src,int radix,long lower,long upper, + long *val); +longlong my_strtoll10(const char *nptr, char **endptr, int *error); +#if SIZEOF_LONG == SIZEOF_LONG_LONG +#define ll2str(A,B,C,D) int2str((A),(B),(C),(D)) +#define longlong2str(A,B,C) int2str((A),(B),(C),1) +#define longlong10_to_str(A,B,C) int10_to_str((A),(B),(C)) +#undef strtoll +#define strtoll(A,B,C) strtol((A),(B),(C)) +#define strtoull(A,B,C) strtoul((A),(B),(C)) +#ifndef HAVE_STRTOULL +#define HAVE_STRTOULL +#endif +#ifndef HAVE_STRTOLL +#define HAVE_STRTOLL +#endif +#else +#ifdef HAVE_LONG_LONG +extern char *ll2str(longlong val,char *dst,int radix, int upcase); +#define longlong2str(A,B,C) ll2str((A),(B),(C),1) +extern char *longlong10_to_str(longlong val,char *dst,int radix); +#if (!defined(HAVE_STRTOULL) || defined(NO_STRTOLL_PROTO)) +extern longlong strtoll(const char *str, char **ptr, int base); +extern ulonglong strtoull(const char *str, char **ptr, int base); +#endif +#endif +#endif + +/* my_vsnprintf.c */ + +extern size_t my_vsnprintf(char *str, size_t n, + const char *format, va_list ap); +extern size_t my_snprintf(char *to, size_t n, const char *fmt, ...) + ATTRIBUTE_FORMAT(printf, 3, 4); + +#if defined(__cplusplus) +} +#endif + +/* + LEX_STRING -- a pair of a C-string and its length. + (it's part of the plugin API as a MYSQL_LEX_STRING) +*/ + +typedef struct st_mysql_lex_string LEX_STRING; + +#define STRING_WITH_LEN(X) (X), ((size_t) (sizeof(X) - 1)) +#define USTRING_WITH_LEN(X) ((uchar*) X), ((size_t) (sizeof(X) - 1)) +#define C_STRING_WITH_LEN(X) ((char *) (X)), ((size_t) (sizeof(X) - 1)) + +/* A variant with const */ +struct st_mysql_const_lex_string +{ + const char *str; + size_t length; +}; +typedef struct st_mysql_const_lex_string LEX_CSTRING; + +/* A variant with const and unsigned */ +struct st_mysql_const_unsigned_lex_string +{ + const uchar *str; + size_t length; +}; +typedef struct st_mysql_const_unsigned_lex_string LEX_CUSTRING; + +/* SPACE_INT is a word that contains only spaces */ +#if SIZEOF_INT == 4 +#define SPACE_INT 0x20202020 +#elif SIZEOF_INT == 8 +#define SPACE_INT 0x2020202020202020 +#else +#error define the appropriate constant for a word full of spaces +#endif + +/** + Skip trailing space. + + On most systems reading memory in larger chunks (ideally equal to the size of + the chinks that the machine physically reads from memory) causes fewer memory + access loops and hence increased performance. + This is why the 'int' type is used : it's closest to that (according to how + it's defined in C). + So when we determine the amount of whitespace at the end of a string we do + the following : + 1. We divide the string into 3 zones : + a) from the start of the string (__start) to the first multiple + of sizeof(int) (__start_words) + b) from the end of the string (__end) to the last multiple of sizeof(int) + (__end_words) + c) a zone that is aligned to sizeof(int) and can be safely accessed + through an int * + 2. We start comparing backwards from (c) char-by-char. If all we find is + space then we continue + 3. If there are elements in zone (b) we compare them as unsigned ints to a + int mask (SPACE_INT) consisting of all spaces + 4. Finally we compare the remaining part (a) of the string char by char. + This covers for the last non-space unsigned int from 3. (if any) + + This algorithm works well for relatively larger strings, but it will slow + the things down for smaller strings (because of the additional calculations + and checks compared to the naive method). Thus the barrier of length 20 + is added. + + @param ptr pointer to the input string + @param len the length of the string + @return the last non-space character +*/ + +static inline const uchar *skip_trailing_space(const uchar *ptr,size_t len) +{ + const uchar *end= ptr + len; + + if (len > 20) + { + const uchar *end_words= (const uchar *)(intptr) + (((ulonglong)(intptr)end) / SIZEOF_INT * SIZEOF_INT); + const uchar *start_words= (const uchar *)(intptr) + ((((ulonglong)(intptr)ptr) + SIZEOF_INT - 1) / SIZEOF_INT * SIZEOF_INT); + + DBUG_ASSERT(((ulonglong)(intptr)ptr) >= SIZEOF_INT); + if (end_words > ptr) + { + while (end > end_words && end[-1] == 0x20) + end--; + if (end[-1] == 0x20 && start_words < end_words) + while (end > start_words && ((unsigned *)end)[-1] == SPACE_INT) + end -= SIZEOF_INT; + } + } + while (end > ptr && end[-1] == 0x20) + end--; + return (end); +} + +#ifdef SAFEMALLOC +#define TRASH(A,B) bfill(A, B, 0x8F) +#else +#define TRASH(A,B) /* nothing */ +#endif /* SAFEMALLOC */ + +#endif /* _m_string_h */ diff --git a/mysql_incl/my_aes.h b/mysql_incl/my_aes.h new file mode 100644 index 0000000..8ea128c --- /dev/null +++ b/mysql_incl/my_aes.h @@ -0,0 +1,65 @@ +/* Copyright (C) 2002 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* Header file for my_aes.c */ +/* Wrapper to give simple interface for MySQL to AES standard encryption */ + +#include "mysys/rijndael.h" + +C_MODE_START + +#define AES_KEY_LENGTH 128 /* Must be 128 192 or 256 */ + +/* + my_aes_encrypt - Crypt buffer with AES encryption algorithm. + source - Pointer to data for encryption + source_length - size of encryption data + dest - buffer to place encrypted data (must be large enough) + key - Key to be used for encryption + kel_length - Length of the key. Will handle keys of any length + + returns - size of encrypted data, or negative in case of error. +*/ + +int my_aes_encrypt(const char *source, int source_length, char *dest, + const char *key, int key_length); + +/* + my_aes_decrypt - DeCrypt buffer with AES encryption algorithm. + source - Pointer to data for decryption + source_length - size of encrypted data + dest - buffer to place decrypted data (must be large enough) + key - Key to be used for decryption + kel_length - Length of the key. Will handle keys of any length + + returns - size of original data, or negative in case of error. +*/ + + +int my_aes_decrypt(const char *source, int source_length, char *dest, + const char *key, int key_length); + +/* + my_aes_get_size - get size of buffer which will be large enough for encrypted + data + source_length - length of data to be encrypted + + returns - size of buffer required to store encrypted data +*/ + +int my_aes_get_size(int source_length); + +C_MODE_END diff --git a/mysql_incl/my_alarm.h b/mysql_incl/my_alarm.h new file mode 100644 index 0000000..dd2d564 --- /dev/null +++ b/mysql_incl/my_alarm.h @@ -0,0 +1,58 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + File to include when we want to use alarm or a loop_counter to display + some information when a program is running +*/ +#ifndef _my_alarm_h +#define _my_alarm_h +#ifdef __cplusplus +extern "C" { +#endif + +extern int volatile my_have_got_alarm; +extern ulong my_time_to_wait_for_lock; + +#if defined(HAVE_ALARM) && !defined(NO_ALARM_LOOP) +#include +#define ALARM_VARIABLES uint alarm_old=0; \ + sig_return alarm_signal=0 +#define ALARM_INIT my_have_got_alarm=0 ; \ + alarm_old=(uint) alarm(MY_HOW_OFTEN_TO_ALARM); \ + alarm_signal=signal(SIGALRM,my_set_alarm_variable); +#define ALARM_END (void) signal(SIGALRM,alarm_signal); \ + (void) alarm(alarm_old); +#define ALARM_TEST my_have_got_alarm +#ifdef DONT_REMEMBER_SIGNAL +#define ALARM_REINIT (void) alarm(MY_HOW_OFTEN_TO_ALARM); \ + (void) signal(SIGALRM,my_set_alarm_variable);\ + my_have_got_alarm=0; +#else +#define ALARM_REINIT (void) alarm((uint) MY_HOW_OFTEN_TO_ALARM); \ + my_have_got_alarm=0; +#endif /* DONT_REMEMBER_SIGNAL */ +#else +#define ALARM_VARIABLES long alarm_pos=0,alarm_end_pos=MY_HOW_OFTEN_TO_WRITE-1 +#define ALARM_INIT +#define ALARM_END +#define ALARM_TEST (alarm_pos++ >= alarm_end_pos) +#define ALARM_REINIT alarm_end_pos+=MY_HOW_OFTEN_TO_WRITE +#endif /* HAVE_ALARM */ + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/my_alloc.h b/mysql_incl/my_alloc.h new file mode 100644 index 0000000..6ade4d0 --- /dev/null +++ b/mysql_incl/my_alloc.h @@ -0,0 +1,51 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Data structures for mysys/my_alloc.c (root memory allocator) +*/ + +#ifndef _my_alloc_h +#define _my_alloc_h + +#define ALLOC_MAX_BLOCK_TO_DROP 4096 +#define ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP 10 + +typedef struct st_used_mem +{ /* struct for once_alloc (block) */ + struct st_used_mem *next; /* Next block in use */ + size_t left; /* memory left in block */ + size_t size; /* size of block */ +} USED_MEM; + + +typedef struct st_mem_root +{ + USED_MEM *free; /* blocks with free memory in it */ + USED_MEM *used; /* blocks almost without free memory */ + USED_MEM *pre_alloc; /* preallocated block */ + /* if block have less memory it will be put in 'used' list */ + size_t min_malloc; + size_t block_size; /* initial block size */ + unsigned int block_num; /* allocated blocks counter */ + /* + first free block in queue test counter (if it exceed + MAX_BLOCK_USAGE_BEFORE_DROP block will be dropped in 'used' list) + */ + unsigned int first_block_usage; + + void (*error_handler)(void); +} MEM_ROOT; +#endif diff --git a/mysql_incl/my_atomic.h b/mysql_incl/my_atomic.h new file mode 100644 index 0000000..40b8895 --- /dev/null +++ b/mysql_incl/my_atomic.h @@ -0,0 +1,254 @@ +/* Copyright (C) 2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + This header defines five atomic operations: + + my_atomic_add#(&var, what) + add 'what' to *var, and return the old value of *var + + my_atomic_fas#(&var, what) + 'Fetch And Store' + store 'what' in *var, and return the old value of *var + + my_atomic_cas#(&var, &old, new) + 'Compare And Swap' + if *var is equal to *old, then store 'new' in *var, and return TRUE + otherwise store *var in *old, and return FALSE + + my_atomic_load#(&var) + return *var + + my_atomic_store#(&var, what) + store 'what' in *var + + '#' is substituted by a size suffix - 8, 16, 32, or ptr + (e.g. my_atomic_add8, my_atomic_fas32, my_atomic_casptr). + + NOTE This operations are not always atomic, so they always must be + enclosed in my_atomic_rwlock_rdlock(lock)/my_atomic_rwlock_rdunlock(lock) + or my_atomic_rwlock_wrlock(lock)/my_atomic_rwlock_wrunlock(lock). + Hint: if a code block makes intensive use of atomic ops, it make sense + to take/release rwlock once for the whole block, not for every statement. + + On architectures where these operations are really atomic, rwlocks will + be optimized away. + 8- and 16-bit atomics aren't implemented for windows (see generic-msvc.h), + but can be added, if necessary. +*/ + +#ifndef my_atomic_rwlock_init + +#define intptr void * + +#ifndef MY_ATOMIC_MODE_RWLOCKS +#include "atomic/nolock.h" +#endif + +#ifndef make_atomic_cas_body +/* nolock.h was not able to generate even a CAS function, fall back */ +#include "atomic/rwlock.h" +#else +/* define missing functions by using the already generated ones */ +#ifndef make_atomic_add_body +#define make_atomic_add_body(S) \ + int ## S tmp=*a; \ + while (!my_atomic_cas ## S(a, &tmp, tmp+v)); \ + v=tmp; +#endif +#ifndef make_atomic_fas_body +#define make_atomic_fas_body(S) \ + int ## S tmp=*a; \ + while (!my_atomic_cas ## S(a, &tmp, v)); \ + v=tmp; +#endif +#ifndef make_atomic_load_body +#define make_atomic_load_body(S) \ + ret= 0; /* avoid compiler warning */ \ + (void)(my_atomic_cas ## S(a, &ret, ret)); +#endif +#ifndef make_atomic_store_body +#define make_atomic_store_body(S) \ + (void)(my_atomic_fas ## S (a, v)); +#endif +#endif + +/* + transparent_union doesn't work in g++ + Bug ? + + Darwin's gcc doesn't want to put pointers in a transparent_union + when built with -arch ppc64. Complains: + warning: 'transparent_union' attribute ignored +*/ +#if defined(__GNUC__) && !defined(__cplusplus) && \ + ! (defined(__APPLE__) && defined(_ARCH_PPC64)) +/* + we want to be able to use my_atomic_xxx functions with + both signed and unsigned integers. But gcc will issue a warning + "passing arg N of `my_atomic_XXX' as [un]signed due to prototype" + if the signedness of the argument doesn't match the prototype, or + "pointer targets in passing argument N of my_atomic_XXX differ in signedness" + if int* is used where uint* is expected (or vice versa). + Let's shut these warnings up +*/ +#define make_transparent_unions(S) \ + typedef union { \ + int ## S i; \ + uint ## S u; \ + } U_ ## S __attribute__ ((transparent_union)); \ + typedef union { \ + int ## S volatile *i; \ + uint ## S volatile *u; \ + } Uv_ ## S __attribute__ ((transparent_union)); +#define uintptr intptr +make_transparent_unions(8) +make_transparent_unions(16) +make_transparent_unions(32) +make_transparent_unions(ptr) +#undef uintptr +#undef make_transparent_unions +#define a U_a.i +#define cmp U_cmp.i +#define v U_v.i +#define set U_set.i +#else +#define U_32 int32 +#define U_ptr intptr +#define Uv_32 int32 +#define Uv_ptr intptr +#define U_a volatile *a +#define U_cmp *cmp +#define U_v v +#define U_set set +#endif /* __GCC__ transparent_union magic */ + +#ifdef HAVE_INLINE + +#define make_atomic_cas(S) \ +STATIC_INLINE int my_atomic_cas ## S(Uv_ ## S U_a, \ + Uv_ ## S U_cmp, U_ ## S U_set) \ +{ \ + int8 ret; \ + make_atomic_cas_body(S); \ + return ret; \ +} + +#define make_atomic_add(S) \ +STATIC_INLINE int ## S my_atomic_add ## S( \ + Uv_ ## S U_a, U_ ## S U_v) \ +{ \ + make_atomic_add_body(S); \ + return v; \ +} + +#define make_atomic_fas(S) \ +STATIC_INLINE int ## S my_atomic_fas ## S( \ + Uv_ ## S U_a, U_ ## S U_v) \ +{ \ + make_atomic_fas_body(S); \ + return v; \ +} + +#define make_atomic_load(S) \ +STATIC_INLINE int ## S my_atomic_load ## S(Uv_ ## S U_a) \ +{ \ + int ## S ret; \ + make_atomic_load_body(S); \ + return ret; \ +} + +#define make_atomic_store(S) \ +STATIC_INLINE void my_atomic_store ## S( \ + Uv_ ## S U_a, U_ ## S U_v) \ +{ \ + make_atomic_store_body(S); \ +} + +#else /* no inline functions */ + +#define make_atomic_add(S) \ +extern int ## S my_atomic_add ## S(Uv_ ## S U_a, U_ ## S U_v); + +#define make_atomic_fas(S) \ +extern int ## S my_atomic_fas ## S(Uv_ ## S U_a, U_ ## S U_v); + +#define make_atomic_cas(S) \ +extern int my_atomic_cas ## S(Uv_ ## S U_a, Uv_ ## S U_cmp, U_ ## S U_set); + +#define make_atomic_load(S) \ +extern int ## S my_atomic_load ## S(Uv_ ## S U_a); + +#define make_atomic_store(S) \ +extern void my_atomic_store ## S(Uv_ ## S U_a, U_ ## S U_v); + +#endif + +make_atomic_cas(32) +make_atomic_cas(ptr) + +make_atomic_add(32) + +make_atomic_load(32) +make_atomic_load(ptr) + +make_atomic_fas(32) +make_atomic_fas(ptr) + +make_atomic_store(32) +make_atomic_store(ptr) + +#ifdef _atomic_h_cleanup_ +#include _atomic_h_cleanup_ +#undef _atomic_h_cleanup_ +#endif + +#undef U_32 +#undef U_ptr +#undef a +#undef cmp +#undef v +#undef set +#undef U_a +#undef U_cmp +#undef U_v +#undef U_set +#undef make_atomic_add +#undef make_atomic_cas +#undef make_atomic_load +#undef make_atomic_store +#undef make_atomic_fas +#undef make_atomic_add_body +#undef make_atomic_cas_body +#undef make_atomic_load_body +#undef make_atomic_store_body +#undef make_atomic_fas_body +#undef intptr + +/* + the macro below defines (as an expression) the code that + will be run in spin-loops. Intel manuals recummend to have PAUSE there. + It is expected to be defined in include/atomic/ *.h files +*/ +#ifndef LF_BACKOFF +#define LF_BACKOFF (1) +#endif + +#define MY_ATOMIC_OK 0 +#define MY_ATOMIC_NOT_1CPU 1 +extern int my_atomic_initialize(); + +#endif + diff --git a/mysql_incl/my_attribute.h b/mysql_incl/my_attribute.h new file mode 100644 index 0000000..8309d85 --- /dev/null +++ b/mysql_incl/my_attribute.h @@ -0,0 +1,63 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Helper macros used for setting different __attributes__ + on functions in a portable fashion +*/ + +#ifndef _my_attribute_h +#define _my_attribute_h + +/* + Disable __attribute__() on gcc < 2.7, g++ < 3.4, and non-gcc compilers. + Some forms of __attribute__ are actually supported in earlier versions of + g++, but we just disable them all because we only use them to generate + compilation warnings. +*/ +#ifndef __attribute__ +# if !defined(__GNUC__) +# define __attribute__(A) +# elif GCC_VERSION < 2008 +# define __attribute__(A) +# elif defined(__cplusplus) && GCC_VERSION < 3004 +# define __attribute__(A) +# endif +#endif + +/* + __attribute__((format(...))) is only supported in gcc >= 2.8 and g++ >= 3.4 + But that's already covered by the __attribute__ tests above, so this is + just a convenience macro. +*/ +#ifndef ATTRIBUTE_FORMAT +# define ATTRIBUTE_FORMAT(style, m, n) __attribute__((format(style, m, n))) +#endif + +/* + + __attribute__((format(...))) on a function pointer is not supported + until gcc 3.1 +*/ +#ifndef ATTRIBUTE_FORMAT_FPTR +# if (GCC_VERSION >= 3001) +# define ATTRIBUTE_FORMAT_FPTR(style, m, n) ATTRIBUTE_FORMAT(style, m, n) +# else +# define ATTRIBUTE_FORMAT_FPTR(style, m, n) +# endif /* GNUC >= 3.1 */ +#endif + + +#endif diff --git a/mysql_incl/my_base.h b/mysql_incl/my_base.h new file mode 100644 index 0000000..e228b39 --- /dev/null +++ b/mysql_incl/my_base.h @@ -0,0 +1,626 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* This file includes constants used with all databases */ + +#ifndef _my_base_h +#define _my_base_h + +#ifndef stdin /* Included first in handler */ +#define CHSIZE_USED +#include +#include /* This includes types */ +#include +#include +#include + +#ifndef EOVERFLOW +#define EOVERFLOW 84 +#endif + +#if !defined(USE_MY_FUNC) && !defined(THREAD) +#include /* For faster code, after test */ +#endif /* USE_MY_FUNC */ +#endif /* stdin */ +#include + +/* The following is bits in the flag parameter to ha_open() */ + +#define HA_OPEN_ABORT_IF_LOCKED 0 /* default */ +#define HA_OPEN_WAIT_IF_LOCKED 1 +#define HA_OPEN_IGNORE_IF_LOCKED 2 +#define HA_OPEN_TMP_TABLE 4 /* Table is a temp table */ +#define HA_OPEN_DELAY_KEY_WRITE 8 /* Don't update index */ +#define HA_OPEN_ABORT_IF_CRASHED 16 +#define HA_OPEN_FOR_REPAIR 32 /* open even if crashed */ +#define HA_OPEN_FROM_SQL_LAYER 64 +#define HA_OPEN_MMAP 128 /* open memory mapped */ +#define HA_OPEN_COPY 256 /* Open copy (for repair) */ +/* Internal temp table, used for temporary results */ +#define HA_OPEN_INTERNAL_TABLE 512 + +/* The following is parameter to ha_rkey() how to use key */ + +/* + We define a complete-field prefix of a key value as a prefix where + the last included field in the prefix contains the full field, not + just some bytes from the start of the field. A partial-field prefix + is allowed to contain only a few first bytes from the last included + field. + + Below HA_READ_KEY_EXACT, ..., HA_READ_BEFORE_KEY can take a + complete-field prefix of a key value as the search + key. HA_READ_PREFIX and HA_READ_PREFIX_LAST could also take a + partial-field prefix, but currently (4.0.10) they are only used with + complete-field prefixes. MySQL uses a padding trick to implement + LIKE 'abc%' queries. + + NOTE that in InnoDB HA_READ_PREFIX_LAST will NOT work with a + partial-field prefix because InnoDB currently strips spaces from the + end of varchar fields! +*/ + +enum ha_rkey_function { + HA_READ_KEY_EXACT, /* Find first record else error */ + HA_READ_KEY_OR_NEXT, /* Record or next record */ + HA_READ_KEY_OR_PREV, /* Record or previous */ + HA_READ_AFTER_KEY, /* Find next rec. after key-record */ + HA_READ_BEFORE_KEY, /* Find next rec. before key-record */ + HA_READ_PREFIX, /* Key which as same prefix */ + HA_READ_PREFIX_LAST, /* Last key with the same prefix */ + HA_READ_PREFIX_LAST_OR_PREV, /* Last or prev key with the same prefix */ + HA_READ_MBR_CONTAIN, + HA_READ_MBR_INTERSECT, + HA_READ_MBR_WITHIN, + HA_READ_MBR_DISJOINT, + HA_READ_MBR_EQUAL +}; + + /* Key algorithm types */ + +enum ha_key_alg { + HA_KEY_ALG_UNDEF= 0, /* Not specified (old file) */ + HA_KEY_ALG_BTREE= 1, /* B-tree, default one */ + HA_KEY_ALG_RTREE= 2, /* R-tree, for spatial searches */ + HA_KEY_ALG_HASH= 3, /* HASH keys (HEAP tables) */ + HA_KEY_ALG_FULLTEXT= 4 /* FULLTEXT (MyISAM tables) */ +}; + + /* Index and table build methods */ + +enum ha_build_method { + HA_BUILD_DEFAULT, + HA_BUILD_ONLINE, + HA_BUILD_OFFLINE +}; + + /* Storage media types */ + +enum ha_storage_media { + HA_SM_DEFAULT= 0, /* Not specified (engine default) */ + HA_SM_DISK= 1, /* DISK storage */ + HA_SM_MEMORY= 2 /* MAIN MEMORY storage */ +}; + + /* The following is parameter to ha_extra() */ + +enum ha_extra_function { + HA_EXTRA_NORMAL=0, /* Optimize for space (def) */ + HA_EXTRA_QUICK=1, /* Optimize for speed */ + HA_EXTRA_NOT_USED=2, + HA_EXTRA_CACHE=3, /* Cache record in HA_rrnd() */ + HA_EXTRA_NO_CACHE=4, /* End caching of records (def) */ + HA_EXTRA_NO_READCHECK=5, /* No readcheck on update */ + HA_EXTRA_READCHECK=6, /* Use readcheck (def) */ + HA_EXTRA_KEYREAD=7, /* Read only key to database */ + HA_EXTRA_NO_KEYREAD=8, /* Normal read of records (def) */ + HA_EXTRA_NO_USER_CHANGE=9, /* No user is allowed to write */ + HA_EXTRA_KEY_CACHE=10, + HA_EXTRA_NO_KEY_CACHE=11, + HA_EXTRA_WAIT_LOCK=12, /* Wait until file is avalably (def) */ + HA_EXTRA_NO_WAIT_LOCK=13, /* If file is locked, return quickly */ + HA_EXTRA_WRITE_CACHE=14, /* Use write cache in ha_write() */ + HA_EXTRA_FLUSH_CACHE=15, /* flush write_record_cache */ + HA_EXTRA_NO_KEYS=16, /* Remove all update of keys */ + HA_EXTRA_KEYREAD_CHANGE_POS=17, /* Keyread, but change pos */ + /* xxxxchk -r must be used */ + HA_EXTRA_REMEMBER_POS=18, /* Remember pos for next/prev */ + HA_EXTRA_RESTORE_POS=19, + HA_EXTRA_REINIT_CACHE=20, /* init cache from current record */ + HA_EXTRA_FORCE_REOPEN=21, /* Datafile have changed on disk */ + HA_EXTRA_FLUSH, /* Flush tables to disk */ + HA_EXTRA_NO_ROWS, /* Don't write rows */ + HA_EXTRA_RESET_STATE, /* Reset positions */ + HA_EXTRA_IGNORE_DUP_KEY, /* Dup keys don't rollback everything*/ + HA_EXTRA_NO_IGNORE_DUP_KEY, + HA_EXTRA_PREPARE_FOR_DROP, + HA_EXTRA_PREPARE_FOR_UPDATE, /* Remove read cache if problems */ + HA_EXTRA_PRELOAD_BUFFER_SIZE, /* Set buffer size for preloading */ + /* + On-the-fly switching between unique and non-unique key inserting. + */ + HA_EXTRA_CHANGE_KEY_TO_UNIQUE, + HA_EXTRA_CHANGE_KEY_TO_DUP, + /* + When using HA_EXTRA_KEYREAD, overwrite only key member fields and keep + other fields intact. When this is off (by default) InnoDB will use memcpy + to overwrite entire row. + */ + HA_EXTRA_KEYREAD_PRESERVE_FIELDS, + HA_EXTRA_MMAP, + /* + Ignore if the a tuple is not found, continue processing the + transaction and ignore that 'row'. Needed for idempotency + handling on the slave + + Currently only used by NDB storage engine. Partition handler ignores flag. + */ + HA_EXTRA_IGNORE_NO_KEY, + HA_EXTRA_NO_IGNORE_NO_KEY, + /* + Mark the table as a log table. For some handlers (e.g. CSV) this results + in a special locking for the table. + */ + HA_EXTRA_MARK_AS_LOG_TABLE, + /* + Informs handler that write_row() which tries to insert new row into the + table and encounters some already existing row with same primary/unique + key can replace old row with new row instead of reporting error (basically + it informs handler that we do REPLACE instead of simple INSERT). + Off by default. + */ + HA_EXTRA_WRITE_CAN_REPLACE, + HA_EXTRA_WRITE_CANNOT_REPLACE, + /* + Inform handler that delete_row()/update_row() cannot batch deletes/updates + and should perform them immediately. This may be needed when table has + AFTER DELETE/UPDATE triggers which access to subject table. + These flags are reset by the handler::extra(HA_EXTRA_RESET) call. + */ + HA_EXTRA_DELETE_CANNOT_BATCH, + HA_EXTRA_UPDATE_CANNOT_BATCH, + /* + Inform handler that an "INSERT...ON DUPLICATE KEY UPDATE" will be + executed. This condition is unset by HA_EXTRA_NO_IGNORE_DUP_KEY. + */ + HA_EXTRA_INSERT_WITH_UPDATE, + /* Inform handler that we will do a rename */ + HA_EXTRA_PREPARE_FOR_RENAME, + /* + Special actions for MERGE tables. + */ + HA_EXTRA_ADD_CHILDREN_LIST, + HA_EXTRA_ATTACH_CHILDREN, + HA_EXTRA_IS_ATTACHED_CHILDREN, + HA_EXTRA_DETACH_CHILDREN, + HA_EXTRA_ORDERBY_LIMIT, + HA_EXTRA_NO_ORDERBY_LIMIT, + /* Inform handler we will force a close as part of flush */ + HA_EXTRA_PREPARE_FOR_FORCED_CLOSE, + HA_EXTRA_ALLOW_LOG_DELETE +}; + +/* Compatible option, to be deleted in 6.0 */ +#define HA_EXTRA_PREPARE_FOR_DELETE HA_EXTRA_PREPARE_FOR_DROP + + /* The following is parameter to ha_panic() */ + +enum ha_panic_function { + HA_PANIC_CLOSE, /* Close all databases */ + HA_PANIC_WRITE, /* Unlock and write status */ + HA_PANIC_READ /* Lock and read keyinfo */ +}; + + /* The following is parameter to ha_create(); keytypes */ + +enum ha_base_keytype { + HA_KEYTYPE_END=0, + HA_KEYTYPE_TEXT=1, /* Key is sorted as letters */ + HA_KEYTYPE_BINARY=2, /* Key is sorted as unsigned chars */ + HA_KEYTYPE_SHORT_INT=3, + HA_KEYTYPE_LONG_INT=4, + HA_KEYTYPE_FLOAT=5, + HA_KEYTYPE_DOUBLE=6, + HA_KEYTYPE_NUM=7, /* Not packed num with pre-space */ + HA_KEYTYPE_USHORT_INT=8, + HA_KEYTYPE_ULONG_INT=9, + HA_KEYTYPE_LONGLONG=10, + HA_KEYTYPE_ULONGLONG=11, + HA_KEYTYPE_INT24=12, + HA_KEYTYPE_UINT24=13, + HA_KEYTYPE_INT8=14, + /* Varchar (0-255 bytes) with length packed with 1 byte */ + HA_KEYTYPE_VARTEXT1=15, /* Key is sorted as letters */ + HA_KEYTYPE_VARBINARY1=16, /* Key is sorted as unsigned chars */ + /* Varchar (0-65535 bytes) with length packed with 2 bytes */ + HA_KEYTYPE_VARTEXT2=17, /* Key is sorted as letters */ + HA_KEYTYPE_VARBINARY2=18, /* Key is sorted as unsigned chars */ + HA_KEYTYPE_BIT=19 +}; + +#define HA_MAX_KEYTYPE 31 /* Must be log2-1 */ + +/* + These flags kan be OR:ed to key-flag + Note that these can only be up to 16 bits! +*/ + +#define HA_NOSAME 1 /* Set if not dupplicated records */ +#define HA_PACK_KEY 2 /* Pack string key to previous key */ +#define HA_AUTO_KEY 16 +#define HA_BINARY_PACK_KEY 32 /* Packing of all keys to prev key */ +#define HA_FULLTEXT 128 /* For full-text search */ +#define HA_UNIQUE_CHECK 256 /* Check the key for uniqueness */ +#define HA_SPATIAL 1024 /* For spatial search */ +#define HA_NULL_ARE_EQUAL 2048 /* NULL in key are cmp as equal */ +#define HA_GENERATED_KEY 8192 /* Automaticly generated key */ +#define HA_RTREE_INDEX 16384 /* For RTREE search */ + + /* The combination of the above can be used for key type comparison. */ +#define HA_KEYFLAG_MASK (HA_NOSAME | HA_PACK_KEY | HA_AUTO_KEY | \ + HA_BINARY_PACK_KEY | HA_FULLTEXT | HA_UNIQUE_CHECK | \ + HA_SPATIAL | HA_NULL_ARE_EQUAL | HA_GENERATED_KEY | \ + HA_RTREE_INDEX) + +#define HA_KEY_HAS_PART_KEY_SEG 65536 /* Key contains partial segments */ + + /* Automatic bits in key-flag */ + +#define HA_SPACE_PACK_USED 4 /* Test for if SPACE_PACK used */ +#define HA_VAR_LENGTH_KEY 8 +#define HA_NULL_PART_KEY 64 +#define HA_USES_COMMENT 4096 +#define HA_USES_PARSER 16384 /* Fulltext index uses [pre]parser */ +#define HA_USES_BLOCK_SIZE ((uint) 32768) +#define HA_SORT_ALLOWS_SAME 512 /* Intern bit when sorting records */ +#if MYSQL_VERSION_ID < 0x50200 +/* + Key has a part that can have end space. If this is an unique key + we have to handle it differently from other unique keys as we can find + many matching rows for one key (because end space are not compared) +*/ +#define HA_END_SPACE_KEY 0 /* was: 4096 */ +#else +#error HA_END_SPACE_KEY is obsolete, please remove it +#endif + + + /* These flags can be added to key-seg-flag */ + +#define HA_SPACE_PACK 1 /* Pack space in key-seg */ +#define HA_PART_KEY_SEG 4 /* Used by MySQL for part-key-cols */ +#define HA_VAR_LENGTH_PART 8 +#define HA_NULL_PART 16 +#define HA_BLOB_PART 32 +#define HA_SWAP_KEY 64 +#define HA_REVERSE_SORT 128 /* Sort key in reverse order */ +#define HA_NO_SORT 256 /* do not bother sorting on this keyseg */ +/* + End space in unique/varchar are considered equal. (Like 'a' and 'a ') + Only needed for internal temporary tables. +*/ +#define HA_END_SPACE_ARE_EQUAL 512 +#define HA_BIT_PART 1024 + + /* optionbits for database */ +#define HA_OPTION_PACK_RECORD 1 +#define HA_OPTION_PACK_KEYS 2 +#define HA_OPTION_COMPRESS_RECORD 4 +#define HA_OPTION_LONG_BLOB_PTR 8 /* new ISAM format */ +#define HA_OPTION_TMP_TABLE 16 +#define HA_OPTION_CHECKSUM 32 +#define HA_OPTION_DELAY_KEY_WRITE 64 +#define HA_OPTION_NO_PACK_KEYS 128 /* Reserved for MySQL */ +#define HA_OPTION_CREATE_FROM_ENGINE 256 +#define HA_OPTION_RELIES_ON_SQL_LAYER 512 +#define HA_OPTION_NULL_FIELDS 1024 +#define HA_OPTION_PAGE_CHECKSUM 2048 +#define HA_OPTION_TEMP_COMPRESS_RECORD (1L << 15) /* set by isamchk */ +#define HA_OPTION_READ_ONLY_DATA (1L << 16) /* Set by isamchk */ +#define HA_OPTION_NO_CHECKSUM (1L << 17) +#define HA_OPTION_NO_DELAY_KEY_WRITE (1L << 18) + + /* Bits in flag to create() */ + +#define HA_DONT_TOUCH_DATA 1 /* Don't empty datafile (isamchk) */ +#define HA_PACK_RECORD 2 /* Request packed record format */ +#define HA_CREATE_TMP_TABLE 4 +#define HA_CREATE_CHECKSUM 8 +#define HA_CREATE_KEEP_FILES 16 /* don't overwrite .MYD and MYI */ +#define HA_CREATE_PAGE_CHECKSUM 32 +#define HA_CREATE_DELAY_KEY_WRITE 64 +#define HA_CREATE_RELIES_ON_SQL_LAYER 128 + +/* + The following flags (OR-ed) are passed to handler::info() method. + The method copies misc handler information out of the storage engine + to data structures accessible from MySQL + + Same flags are also passed down to mi_status, myrg_status, etc. +*/ + +/* this one is not used */ +#define HA_STATUS_POS 1 +/* + assuming the table keeps shared actual copy of the 'info' and + local, possibly outdated copy, the following flag means that + it should not try to get the actual data (locking the shared structure) + slightly outdated version will suffice +*/ +#define HA_STATUS_NO_LOCK 2 +/* update the time of the last modification (in handler::update_time) */ +#define HA_STATUS_TIME 4 +/* + update the 'constant' part of the info: + handler::max_data_file_length, max_index_file_length, create_time + sortkey, ref_length, block_size, data_file_name, index_file_name. + handler::table->s->keys_in_use, keys_for_keyread, rec_per_key +*/ +#define HA_STATUS_CONST 8 +/* + update the 'variable' part of the info: + handler::records, deleted, data_file_length, index_file_length, + delete_length, check_time, mean_rec_length +*/ +#define HA_STATUS_VARIABLE 16 +/* + get the information about the key that caused last duplicate value error + update handler::errkey and handler::dupp_ref + see handler::get_dup_key() +*/ +#define HA_STATUS_ERRKEY 32 +/* + update handler::auto_increment_value +*/ +#define HA_STATUS_AUTO 64 + +/* + Errorcodes given by handler functions + + opt_sum_query() assumes these codes are > 1 + Do not add error numbers before HA_ERR_FIRST. + If necessary to add lower numbers, change HA_ERR_FIRST accordingly. +*/ +#define HA_ERR_FIRST 120 /* Copy of first error nr.*/ + +#define HA_ERR_KEY_NOT_FOUND 120 /* Didn't find key on read or update */ +#define HA_ERR_FOUND_DUPP_KEY 121 /* Dupplicate key on write */ +#define HA_ERR_INTERNAL_ERROR 122 /* Internal error */ +#define HA_ERR_RECORD_CHANGED 123 /* Uppdate with is recoverable */ +#define HA_ERR_WRONG_INDEX 124 /* Wrong index given to function */ +#define HA_ERR_CRASHED 126 /* Indexfile is crashed */ +#define HA_ERR_WRONG_IN_RECORD 127 /* Record-file is crashed */ +#define HA_ERR_OUT_OF_MEM 128 /* Record-file is crashed */ +#define HA_ERR_NOT_A_TABLE 130 /* not a MYI file - no signature */ +#define HA_ERR_WRONG_COMMAND 131 /* Command not supported */ +#define HA_ERR_OLD_FILE 132 /* old databasfile */ +#define HA_ERR_NO_ACTIVE_RECORD 133 /* No record read in update() */ +#define HA_ERR_RECORD_DELETED 134 /* A record is not there */ +#define HA_ERR_RECORD_FILE_FULL 135 /* No more room in file */ +#define HA_ERR_INDEX_FILE_FULL 136 /* No more room in file */ +#define HA_ERR_END_OF_FILE 137 /* end in next/prev/first/last */ +#define HA_ERR_UNSUPPORTED 138 /* unsupported extension used */ +#define HA_ERR_TO_BIG_ROW 139 /* Too big row */ +#define HA_WRONG_CREATE_OPTION 140 /* Wrong create option */ +#define HA_ERR_FOUND_DUPP_UNIQUE 141 /* Dupplicate unique on write */ +#define HA_ERR_UNKNOWN_CHARSET 142 /* Can't open charset */ +#define HA_ERR_WRONG_MRG_TABLE_DEF 143 /* conflicting tables in MERGE */ +#define HA_ERR_CRASHED_ON_REPAIR 144 /* Last (automatic?) repair failed */ +#define HA_ERR_CRASHED_ON_USAGE 145 /* Table must be repaired */ +#define HA_ERR_LOCK_WAIT_TIMEOUT 146 +#define HA_ERR_LOCK_TABLE_FULL 147 +#define HA_ERR_READ_ONLY_TRANSACTION 148 /* Updates not allowed */ +#define HA_ERR_LOCK_DEADLOCK 149 +#define HA_ERR_CANNOT_ADD_FOREIGN 150 /* Cannot add a foreign key constr. */ +#define HA_ERR_NO_REFERENCED_ROW 151 /* Cannot add a child row */ +#define HA_ERR_ROW_IS_REFERENCED 152 /* Cannot delete a parent row */ +#define HA_ERR_NO_SAVEPOINT 153 /* No savepoint with that name */ +#define HA_ERR_NON_UNIQUE_BLOCK_SIZE 154 /* Non unique key block size */ +#define HA_ERR_NO_SUCH_TABLE 155 /* The table does not exist in engine */ +#define HA_ERR_TABLE_EXIST 156 /* The table existed in storage engine */ +#define HA_ERR_NO_CONNECTION 157 /* Could not connect to storage engine */ +/* NULLs are not supported in spatial index */ +#define HA_ERR_NULL_IN_SPATIAL 158 +#define HA_ERR_TABLE_DEF_CHANGED 159 /* The table changed in storage engine */ +/* There's no partition in table for given value */ +#define HA_ERR_NO_PARTITION_FOUND 160 +#define HA_ERR_RBR_LOGGING_FAILED 161 /* Row-based binlogging of row failed */ +#define HA_ERR_DROP_INDEX_FK 162 /* Index needed in foreign key constr */ +/* + Upholding foreign key constraints would lead to a duplicate key error + in some other table. +*/ +#define HA_ERR_FOREIGN_DUPLICATE_KEY 163 +/* The table changed in storage engine */ +#define HA_ERR_TABLE_NEEDS_UPGRADE 164 +#define HA_ERR_TABLE_READONLY 165 /* The table is not writable */ + +#define HA_ERR_AUTOINC_READ_FAILED 166 /* Failed to get next autoinc value */ +#define HA_ERR_AUTOINC_ERANGE 167 /* Failed to set row autoinc value */ +#define HA_ERR_GENERIC 168 /* Generic error */ +/* row not actually updated: new values same as the old values */ +#define HA_ERR_RECORD_IS_THE_SAME 169 +/* It is not possible to log this statement */ +#define HA_ERR_LOGGING_IMPOSSIBLE 170 +#define HA_ERR_TABLESPACE_EXIST 171 +/* The event was corrupt, leading to illegal data being read */ +#define HA_ERR_CORRUPT_EVENT 172 +#define HA_ERR_NEW_FILE 173 /* New file format */ +/* The event could not be processed no other handler error happened */ +#define HA_ERR_ROWS_EVENT_APPLY 174 +#define HA_ERR_INITIALIZATION 175 /* Error during initialization */ +#define HA_ERR_FILE_TOO_SHORT 176 /* File too short */ +#define HA_ERR_WRONG_CRC 177 /* Wrong CRC on page */ +#define HA_ERR_LOCK_OR_ACTIVE_TRANSACTION 178 +#define HA_ERR_NO_SUCH_TABLESPACE 179 +#define HA_ERR_TABLESPACE_NOT_EMPTY 180 +#define HA_ERR_TABLESPACE_DATAFILE_EXIST 181 +#define HA_ERR_ROW_NOT_VISIBLE 182 +#define HA_ERR_LAST 182 /* Copy of last error nr */ + +/* Number of different errors */ +#define HA_ERR_ERRORS (HA_ERR_LAST - HA_ERR_FIRST + 1) + + /* Other constants */ + +#define HA_NAMELEN 64 /* Max length of saved filename */ +#define NO_SUCH_KEY (~(uint)0) /* used as a key no. */ + +typedef ulong key_part_map; +#define HA_WHOLE_KEY (~(key_part_map)0) + + /* Intern constants in databases */ + + /* bits in _search */ +#define SEARCH_FIND 1 +#define SEARCH_NO_FIND 2 +#define SEARCH_SAME 4 +#define SEARCH_BIGGER 8 +#define SEARCH_SMALLER 16 +#define SEARCH_SAVE_BUFF 32 +#define SEARCH_UPDATE 64 +#define SEARCH_PREFIX 128 +#define SEARCH_LAST 256 +#define MBR_CONTAIN 512 +#define MBR_INTERSECT 1024 +#define MBR_WITHIN 2048 +#define MBR_DISJOINT 4096 +#define MBR_EQUAL 8192 +#define MBR_DATA 16384 +#define SEARCH_NULL_ARE_EQUAL 32768 /* NULL in keys are equal */ +#define SEARCH_NULL_ARE_NOT_EQUAL 65536 /* NULL in keys are not equal */ +/* Use this when inserting a key in position order */ +#define SEARCH_INSERT SEARCH_NULL_ARE_NOT_EQUAL*2 +/* Only part of the key is specified while reading */ +#define SEARCH_PART_KEY SEARCH_INSERT*2 +/* Used when user key (key 2) contains transaction id's */ +#define SEARCH_USER_KEY_HAS_TRANSID SEARCH_PART_KEY*2 +/* Used when page key (key 1) contains transaction id's */ +#define SEARCH_PAGE_KEY_HAS_TRANSID SEARCH_USER_KEY_HAS_TRANSID*2 + + /* bits in opt_flag */ +#define QUICK_USED 1 +#define READ_CACHE_USED 2 +#define READ_CHECK_USED 4 +#define KEY_READ_USED 8 +#define WRITE_CACHE_USED 16 +#define OPT_NO_ROWS 32 + + /* bits in update */ +#define HA_STATE_CHANGED 1 /* Database has changed */ +#define HA_STATE_AKTIV 2 /* Has a current record */ +#define HA_STATE_WRITTEN 4 /* Record is written */ +#define HA_STATE_DELETED 8 +#define HA_STATE_NEXT_FOUND 16 /* Next found record (record before) */ +#define HA_STATE_PREV_FOUND 32 /* Prev found record (record after) */ +#define HA_STATE_NO_KEY 64 /* Last read didn't find record */ +#define HA_STATE_KEY_CHANGED 128 +#define HA_STATE_WRITE_AT_END 256 /* set in _ps_find_writepos */ +#define HA_STATE_BUFF_SAVED 512 /* If current keybuff is info->buff */ +#define HA_STATE_ROW_CHANGED 1024 /* To invalide ROW cache */ +#define HA_STATE_EXTEND_BLOCK 2048 +#define HA_STATE_RNEXT_SAME 4096 /* rnext_same occupied lastkey2 */ + +/* myisampack expects no more than 32 field types. */ +enum en_fieldtype { + FIELD_LAST=-1,FIELD_NORMAL,FIELD_SKIP_ENDSPACE,FIELD_SKIP_PRESPACE, + FIELD_SKIP_ZERO,FIELD_BLOB,FIELD_CONSTANT,FIELD_INTERVALL,FIELD_ZERO, + FIELD_VARCHAR,FIELD_CHECK, + FIELD_enum_val_count +}; + +enum data_file_type { + STATIC_RECORD, DYNAMIC_RECORD, COMPRESSED_RECORD, BLOCK_RECORD +}; + +/* For key ranges */ + +/* from -inf */ +#define NO_MIN_RANGE 1 + +/* to +inf */ +#define NO_MAX_RANGE 2 + +/* X < key, i.e. not including the left endpoint */ +#define NEAR_MIN 4 + +/* X > key, i.e. not including the right endpoint */ +#define NEAR_MAX 8 + +/* + This flag means that index is a unique index, and the interval is + equivalent to "AND(keypart_i = const_i)", where all of const_i are not NULLs. +*/ +#define UNIQUE_RANGE 16 + +/* + This flag means that the interval is equivalent to + "AND(keypart_i = const_i)", where not all key parts may be used but all of + const_i are not NULLs. +*/ +#define EQ_RANGE 32 + +/* + This flag has the same meaning as UNIQUE_RANGE, except that for at least + one keypart the condition is "keypart IS NULL". +*/ +#define NULL_RANGE 64 + +#define GEOM_FLAG 128 + +#define SKIP_RANGE 256 +#define EMPTY_RANGE 512 + +typedef struct st_key_range +{ + const uchar *key; + uint length; + key_part_map keypart_map; + enum ha_rkey_function flag; +} key_range; + +typedef struct st_key_multi_range +{ + key_range start_key; + key_range end_key; + char *ptr; /* Free to use by caller (ptr to row etc) */ + uint range_flag; /* key range flags see above */ +} KEY_MULTI_RANGE; + + +/* For number of records */ +#ifdef BIG_TABLES +#define rows2double(A) ulonglong2double(A) +typedef my_off_t ha_rows; +#else +#define rows2double(A) (double) (A) +typedef ulong ha_rows; +#endif + +#define HA_POS_ERROR (~ (ha_rows) 0) +#define HA_OFFSET_ERROR (~ (my_off_t) 0) + +#if SYSTEM_SIZEOF_OFF_T == 4 +#define MAX_FILE_SIZE INT_MAX32 +#else +#define MAX_FILE_SIZE LONGLONG_MAX +#endif + +#define HA_VARCHAR_PACKLENGTH(field_length) ((field_length) < 256 ? 1 :2) + +/* invalidator function reference for Query Cache */ +typedef void (* invalidator_by_filename)(const char * filename); + +#endif /* _my_base_h */ diff --git a/mysql_incl/my_bit.h b/mysql_incl/my_bit.h new file mode 100644 index 0000000..2e464e8 --- /dev/null +++ b/mysql_incl/my_bit.h @@ -0,0 +1,109 @@ +/* + Some useful bit functions +*/ + +C_MODE_START +#ifdef HAVE_INLINE + +extern const char _my_bits_nbits[256]; +extern const uchar _my_bits_reverse_table[256]; + +/* + Find smallest X in 2^X >= value + This can be used to divide a number with value by doing a shift instead +*/ + +STATIC_INLINE uint my_bit_log2(ulong value) +{ + uint bit; + for (bit=0 ; value > 1 ; value>>=1, bit++) ; + return bit; +} + +STATIC_INLINE uint my_count_bits(ulonglong v) +{ +#if SIZEOF_LONG_LONG > 4 + /* The following code is a bit faster on 16 bit machines than if we would + only shift v */ + ulong v2=(ulong) (v >> 32); + return (uint) (uchar) (_my_bits_nbits[(uchar) v] + + _my_bits_nbits[(uchar) (v >> 8)] + + _my_bits_nbits[(uchar) (v >> 16)] + + _my_bits_nbits[(uchar) (v >> 24)] + + _my_bits_nbits[(uchar) (v2)] + + _my_bits_nbits[(uchar) (v2 >> 8)] + + _my_bits_nbits[(uchar) (v2 >> 16)] + + _my_bits_nbits[(uchar) (v2 >> 24)]); +#else + return (uint) (uchar) (_my_bits_nbits[(uchar) v] + + _my_bits_nbits[(uchar) (v >> 8)] + + _my_bits_nbits[(uchar) (v >> 16)] + + _my_bits_nbits[(uchar) (v >> 24)]); +#endif +} + +STATIC_INLINE uint my_count_bits_ushort(ushort v) +{ + return _my_bits_nbits[v]; +} + + +/* + Next highest power of two + + SYNOPSIS + my_round_up_to_next_power() + v Value to check + + RETURN + Next or equal power of 2 + Note: 0 will return 0 + + NOTES + Algorithm by Sean Anderson, according to: + http://graphics.stanford.edu/~seander/bithacks.html + (Orignal code public domain) + + Comments shows how this works with 01100000000000000000000000001011 +*/ + +STATIC_INLINE uint32 my_round_up_to_next_power(uint32 v) +{ + v--; /* 01100000000000000000000000001010 */ + v|= v >> 1; /* 01110000000000000000000000001111 */ + v|= v >> 2; /* 01111100000000000000000000001111 */ + v|= v >> 4; /* 01111111110000000000000000001111 */ + v|= v >> 8; /* 01111111111111111100000000001111 */ + v|= v >> 16; /* 01111111111111111111111111111111 */ + return v+1; /* 10000000000000000000000000000000 */ +} + +STATIC_INLINE uint32 my_clear_highest_bit(uint32 v) +{ + uint32 w=v >> 1; + w|= w >> 1; + w|= w >> 2; + w|= w >> 4; + w|= w >> 8; + w|= w >> 16; + return v & w; +} + +STATIC_INLINE uint32 my_reverse_bits(uint32 key) +{ + return + (_my_bits_reverse_table[ key & 255] << 24) | + (_my_bits_reverse_table[(key>> 8) & 255] << 16) | + (_my_bits_reverse_table[(key>>16) & 255] << 8) | + _my_bits_reverse_table[(key>>24) ]; +} + +#else /* HAVE_INLINE */ +extern uint my_bit_log2(ulong value); +extern uint32 my_round_up_to_next_power(uint32 v); +uint32 my_clear_highest_bit(uint32 v); +uint32 my_reverse_bits(uint32 key); +extern uint my_count_bits(ulonglong v); +extern uint my_count_bits_ushort(ushort v); +#endif /* HAVE_INLINE */ +C_MODE_END diff --git a/mysql_incl/my_bitmap.h b/mysql_incl/my_bitmap.h new file mode 100644 index 0000000..d8c9a0c --- /dev/null +++ b/mysql_incl/my_bitmap.h @@ -0,0 +1,182 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _my_bitmap_h_ +#define _my_bitmap_h_ + +#define MY_BIT_NONE (~(uint) 0) + +#include + +typedef uint32 my_bitmap_map; + +typedef struct st_bitmap +{ + my_bitmap_map *bitmap; + uint n_bits; /* number of bits occupied by the above */ + my_bitmap_map last_word_mask; + my_bitmap_map *last_word_ptr; + /* + mutex will be acquired for the duration of each bitmap operation if + thread_safe flag in bitmap_init was set. Otherwise, we optimize by not + acquiring the mutex + */ +#ifdef THREAD + pthread_mutex_t *mutex; +#endif +} MY_BITMAP; + +#ifdef __cplusplus +extern "C" { +#endif +extern void create_last_word_mask(MY_BITMAP *map); +extern my_bool bitmap_init(MY_BITMAP *map, my_bitmap_map *buf, uint n_bits, + my_bool thread_safe); +extern my_bool bitmap_is_clear_all(const MY_BITMAP *map); +extern my_bool bitmap_is_prefix(const MY_BITMAP *map, uint prefix_size); +extern my_bool bitmap_is_set_all(const MY_BITMAP *map); +extern my_bool bitmap_is_subset(const MY_BITMAP *map1, const MY_BITMAP *map2); +extern my_bool bitmap_is_overlapping(const MY_BITMAP *map1, + const MY_BITMAP *map2); +extern my_bool bitmap_test_and_set(MY_BITMAP *map, uint bitmap_bit); +extern my_bool bitmap_test_and_clear(MY_BITMAP *map, uint bitmap_bit); +extern my_bool bitmap_fast_test_and_set(MY_BITMAP *map, uint bitmap_bit); +extern uint bitmap_set_next(MY_BITMAP *map); +extern uint bitmap_get_first(const MY_BITMAP *map); +extern uint bitmap_get_first_set(const MY_BITMAP *map); +extern uint bitmap_bits_set(const MY_BITMAP *map); +extern void bitmap_free(MY_BITMAP *map); +extern void bitmap_set_above(MY_BITMAP *map, uint from_byte, uint use_bit); +extern void bitmap_set_prefix(MY_BITMAP *map, uint prefix_size); +extern void bitmap_intersect(MY_BITMAP *map, const MY_BITMAP *map2); +extern void bitmap_subtract(MY_BITMAP *map, const MY_BITMAP *map2); +extern void bitmap_union(MY_BITMAP *map, const MY_BITMAP *map2); +extern void bitmap_xor(MY_BITMAP *map, const MY_BITMAP *map2); +extern void bitmap_invert(MY_BITMAP *map); +extern void bitmap_copy(MY_BITMAP *map, const MY_BITMAP *map2); + +extern uint bitmap_lock_set_next(MY_BITMAP *map); +extern void bitmap_lock_clear_bit(MY_BITMAP *map, uint bitmap_bit); +#ifdef NOT_USED +extern uint bitmap_lock_bits_set(const MY_BITMAP *map); +extern my_bool bitmap_lock_is_set_all(const MY_BITMAP *map); +extern uint bitmap_lock_get_first(const MY_BITMAP *map); +extern uint bitmap_lock_get_first_set(const MY_BITMAP *map); +extern my_bool bitmap_lock_is_subset(const MY_BITMAP *map1, + const MY_BITMAP *map2); +extern my_bool bitmap_lock_is_prefix(const MY_BITMAP *map, uint prefix_size); +extern my_bool bitmap_lock_is_set(const MY_BITMAP *map, uint bitmap_bit); +extern my_bool bitmap_lock_is_clear_all(const MY_BITMAP *map); +extern my_bool bitmap_lock_cmp(const MY_BITMAP *map1, const MY_BITMAP *map2); +extern void bitmap_lock_set_all(MY_BITMAP *map); +extern void bitmap_lock_clear_all(MY_BITMAP *map); +extern void bitmap_lock_set_bit(MY_BITMAP *map, uint bitmap_bit); +extern void bitmap_lock_flip_bit(MY_BITMAP *map, uint bitmap_bit); +extern void bitmap_lock_set_prefix(MY_BITMAP *map, uint prefix_size); +extern void bitmap_lock_intersect(MY_BITMAP *map, const MY_BITMAP *map2); +extern void bitmap_lock_subtract(MY_BITMAP *map, const MY_BITMAP *map2); +extern void bitmap_lock_union(MY_BITMAP *map, const MY_BITMAP *map2); +extern void bitmap_lock_xor(MY_BITMAP *map, const MY_BITMAP *map2); +extern void bitmap_lock_invert(MY_BITMAP *map); +#endif +/* Fast, not thread safe, bitmap functions */ +#define bitmap_buffer_size(bits) (((bits)+31)/32)*4 +#define no_bytes_in_map(map) (((map)->n_bits + 7)/8) +#define no_words_in_map(map) (((map)->n_bits + 31)/32) +#define bytes_word_aligned(bytes) (4*((bytes + 3)/4)) +#define _bitmap_set_bit(MAP, BIT) (((uchar*)(MAP)->bitmap)[(BIT) / 8] \ + |= (1 << ((BIT) & 7))) +#define _bitmap_flip_bit(MAP, BIT) (((uchar*)(MAP)->bitmap)[(BIT) / 8] \ + ^= (1 << ((BIT) & 7))) +#define _bitmap_clear_bit(MAP, BIT) (((uchar*)(MAP)->bitmap)[(BIT) / 8] \ + &= ~ (1 << ((BIT) & 7))) +#define _bitmap_is_set(MAP, BIT) (uint) (((uchar*)(MAP)->bitmap)[(BIT) / 8] \ + & (1 << ((BIT) & 7))) +/* + WARNING! + + The below symbols are inline functions in DEBUG builds and macros in + non-DEBUG builds. The latter evaluate their 'bit' argument twice. + + NEVER use an increment/decrement operator with the 'bit' argument. + It would work with DEBUG builds, but fails later in production builds! + + FORBIDDEN: bitmap_set_bit($my_bitmap, (field++)->field_index); +*/ +#ifndef DBUG_OFF +static inline void +bitmap_set_bit(MY_BITMAP *map,uint bit) +{ + DBUG_ASSERT(bit < (map)->n_bits); + _bitmap_set_bit(map,bit); +} +static inline void +bitmap_flip_bit(MY_BITMAP *map,uint bit) +{ + DBUG_ASSERT(bit < (map)->n_bits); + _bitmap_flip_bit(map,bit); +} +static inline void +bitmap_clear_bit(MY_BITMAP *map,uint bit) +{ + DBUG_ASSERT(bit < (map)->n_bits); + _bitmap_clear_bit(map,bit); +} +static inline uint +bitmap_is_set(const MY_BITMAP *map,uint bit) +{ + DBUG_ASSERT(bit < (map)->n_bits); + return _bitmap_is_set(map,bit); +} +#else +#define bitmap_set_bit(MAP, BIT) _bitmap_set_bit(MAP, BIT) +#define bitmap_flip_bit(MAP, BIT) _bitmap_flip_bit(MAP, BIT) +#define bitmap_clear_bit(MAP, BIT) _bitmap_clear_bit(MAP, BIT) +#define bitmap_is_set(MAP, BIT) _bitmap_is_set(MAP, BIT) +#endif + +static inline my_bool bitmap_cmp(const MY_BITMAP *map1, const MY_BITMAP *map2) +{ + *(map1)->last_word_ptr|= (map1)->last_word_mask; + *(map2)->last_word_ptr|= (map2)->last_word_mask; + return memcmp((map1)->bitmap, (map2)->bitmap, 4*no_words_in_map((map1)))==0; +} + +#define bitmap_clear_all(MAP) \ + { memset((MAP)->bitmap, 0, 4*no_words_in_map((MAP))); } +#define bitmap_set_all(MAP) \ + (memset((MAP)->bitmap, 0xFF, 4*no_words_in_map((MAP)))) + +/** + check, set and clear a bit of interest of an integer. + + If the bit is out of range @retval -1. Otherwise + bit_is_set @return 0 or 1 reflecting the bit is set or not; + bit_do_set @return 1 (bit is set 1) + bit_do_clear @return 0 (bit is cleared to 0) +*/ + +#define bit_is_set(I,B) (sizeof(I) * CHAR_BIT > (B) ? \ + (((I) & (1ULL << (B))) == 0 ? 0 : 1) : -1) +#define bit_do_set(I,B) (sizeof(I) * CHAR_BIT > (B) ? \ + ((I) |= (1ULL << (B)), 1) : -1) +#define bit_do_clear(I,B) (sizeof(I) * CHAR_BIT > (B) ? \ + ((I) &= ~(1ULL << (B)), 0) : -1) + +#ifdef __cplusplus +} +#endif + +#endif /* _my_bitmap_h_ */ diff --git a/mysql_incl/my_charsets.h b/mysql_incl/my_charsets.h new file mode 100644 index 0000000..ecb0de9 --- /dev/null +++ b/mysql_incl/my_charsets.h @@ -0,0 +1,57 @@ +/* Copyright (C) 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* Character set configuration (hard-coded) */ +#define HAVE_CHARSET_armscii8 1 +#define HAVE_CHARSET_ascii 1 +#define HAVE_CHARSET_big5 1 +#define HAVE_CHARSET_cp1250 1 +#define HAVE_CHARSET_cp1251 1 +#define HAVE_CHARSET_cp1256 1 +#define HAVE_CHARSET_cp1257 1 +#define HAVE_CHARSET_cp850 1 +#define HAVE_CHARSET_cp852 1 +#define HAVE_CHARSET_cp866 1 +#define HAVE_CHARSET_cp932 1 +#define HAVE_CHARSET_dec8 1 +#define HAVE_CHARSET_eucjpms 1 +#define HAVE_CHARSET_euckr 1 +#define HAVE_CHARSET_gb2312 1 +#define HAVE_CHARSET_gbk 1 +#define HAVE_CHARSET_greek 1 +#define HAVE_CHARSET_hebrew 1 +#define HAVE_CHARSET_hp8 1 +#define HAVE_CHARSET_keybcs2 1 +#define HAVE_CHARSET_koi8r 1 +#define HAVE_CHARSET_koi8u 1 +#define HAVE_CHARSET_latin1 1 +#define HAVE_CHARSET_latin2 1 +#define HAVE_CHARSET_latin5 1 +#define HAVE_CHARSET_latin7 1 +#define HAVE_CHARSET_macce 1 +#define HAVE_CHARSET_macroman 1 +#define HAVE_CHARSET_sjis 1 +#define HAVE_CHARSET_swe7 1 +#define HAVE_CHARSET_tis620 1 +#define HAVE_CHARSET_ucs2 1 +#define HAVE_CHARSET_ujis 1 +#define HAVE_CHARSET_utf16 1 +#define HAVE_CHARSET_utf32 1 +#define HAVE_CHARSET_utf8mb3 1 +#define HAVE_CHARSET_utf8mb4 1 +#define HAVE_UCA_COLLATIONS 1 +#define MYSQL_DEFAULT_CHARSET_NAME "latin1" +#define MYSQL_DEFAULT_COLLATION_NAME "latin1_swedish_ci" +#define USE_MB 1 diff --git a/mysql_incl/my_config.h b/mysql_incl/my_config.h new file mode 100644 index 0000000..adea8db --- /dev/null +++ b/mysql_incl/my_config.h @@ -0,0 +1,295 @@ + +/* Headers we may want to use. */ +/* #undef HAVE_ALLOCA_H */ +/* #undef HAVE_ARPA_INET_H */ +/* #undef HAVE_CRYPT_H */ +/* #undef HAVE_DIRENT_H */ +/* #undef HAVE_EXECINFO_H */ +#define HAVE_FCNTL_H 1 +/* #undef HAVE_FENV_H */ +#define HAVE_FLOAT_H 1 +/* #undef HAVE_FPU_CONTROL_H */ +/* #undef HAVE_GRP_H */ +/* #undef HAVE_IEEEFP_H */ +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MEMORY_H 1 +/* #undef HAVE_NETINET_IN_H */ +/* #undef HAVE_PATHS_H */ +/* #undef HAVE_PWD_H */ +/* #undef HAVE_SCHED_H */ +/* #undef HAVE_SELECT_H */ +#define HAVE_STDDEF_H 1 +#define HAVE_STDLIB_H 1 +/* #undef HAVE_STRINGS_H */ +#define HAVE_STRING_H 1 +/* #undef HAVE_SYNCH_H */ +/* #undef HAVE_SYSENT_H */ +/* #undef HAVE_SYS_FPU_H */ +/* #undef HAVE_SYS_IOCTL_H */ +/* #undef HAVE_SYS_IPC_H */ +/* #undef HAVE_SYS_MMAN_H */ +/* #undef HAVE_SYS_PRCTL_H */ +/* #undef HAVE_SYS_SELECT_H */ +/* #undef HAVE_SYS_SHM_H */ +/* #undef HAVE_SYS_SOCKET_H */ +#define HAVE_SYS_STAT_H 1 +/* #undef HAVE_SYS_STREAM_H */ +#define HAVE_SYS_TIMEB_H 1 +#define HAVE_SYS_TYPES_H 1 +/* #undef HAVE_SYS_UN_H */ +/* #undef HAVE_TERMIOS_H */ +/* #undef HAVE_TERMIO_H */ +/* #undef HAVE_UNISTD_H */ +/* #undef HAVE_UTIME_H */ + +/* Functions we may want to use. */ +#define HAVE_ACCESS 1 +/* #undef HAVE_AIOWAIT */ +/* #undef HAVE_ALARM */ +/* #undef HAVE_ALLOCA */ +/* #undef HAVE_BCMP */ +/* #undef HAVE_BFILL */ +/* #undef HAVE_BMOVE */ +/* #undef HAVE_BZERO */ +/* #undef HAVE_CLOCK_GETTIME */ +/* #undef HAVE_COMPRESS */ +/* #undef HAVE_CRYPT */ +/* #undef HAVE_DLERROR */ +/* #undef HAVE_DLOPEN */ +/* #undef HAVE_FCHMOD */ +/* #undef HAVE_FCNTL */ +/* #undef HAVE_FCONVERT */ +/* #undef HAVE_FDATASYNC */ +/* #undef HAVE_FESETROUND */ +/* #undef HAVE_FINITE */ +/* #undef HAVE_FP_EXCEPT */ +/* #undef HAVE_FSEEKO */ +/* #undef HAVE_FSYNC */ +/* #undef HAVE_GETADDRINFO */ +#define HAVE_GETCWD 1 +/* #undef HAVE_GETHOSTBYADDR_R */ +/* #undef HAVE_GETHOSTBYNAME_R */ +/* #undef HAVE_GETHRTIME */ +/* #undef HAVE_GETNAMEINFO */ +/* #undef HAVE_GETPAGESIZE */ +/* #undef HAVE_GETPASS */ +/* #undef HAVE_GETPASSPHRASE */ +/* #undef HAVE_GETPWNAM */ +/* #undef HAVE_GETPWUID */ +/* #undef HAVE_GETRLIMIT */ +/* #undef HAVE_GETRUSAGE */ +/* #undef HAVE_GETWD */ +/* #undef HAVE_GMTIME_R */ +/* #undef HAVE_INITGROUPS */ +/* #undef HAVE_ISNAN */ +#define HAVE_LDIV 1 +/* #undef HAVE_LOCALTIME_R */ +/* #undef HAVE_LOG2 */ +#define HAVE_LONGJMP 1 +/* #undef HAVE_LSTAT */ +/* #undef HAVE_MADVISE */ +/* #undef HAVE_DECL_MADVISE */ +/* #undef HAVE_MALLINFO */ +#define HAVE_MEMCPY 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMMOVE 1 +/* #undef HAVE_MKSTEMP */ +/* #undef HAVE_MLOCK */ +/* #undef HAVE_MLOCKALL */ +/* #undef HAVE_MMAP */ +/* #undef HAVE_MMAP64 */ +#define HAVE_PERROR 1 +/* #undef HAVE_POLL */ +/* #undef HAVE_PREAD */ +/* #undef HAVE_PTHREAD_ATTR_CREATE */ +/* #undef HAVE_PTHREAD_ATTR_GETSTACKSIZE */ +/* #undef HAVE_PTHREAD_ATTR_SETPRIO */ +/* #undef HAVE_PTHREAD_ATTR_SETSCHEDPARAM */ +/* #undef HAVE_PTHREAD_ATTR_SETSCOPE */ +/* #undef HAVE_PTHREAD_ATTR_SETSTACKSIZE */ +/* #undef HAVE_PTHREAD_CONDATTR_CREATE */ +/* #undef HAVE_PTHREAD_INIT */ +/* #undef HAVE_PTHREAD_KEY_DELETE */ +/* #undef HAVE_PTHREAD_KEY_DELETE */ +/* #undef HAVE_PTHREAD_KILL */ +/* #undef HAVE_PTHREAD_RWLOCK_RDLOCK */ +/* #undef HAVE_PTHREAD_SETPRIO_NP */ +/* #undef HAVE_PTHREAD_SETSCHEDPARAM */ +/* #undef HAVE_PTHREAD_SIGMASK */ +/* #undef HAVE_PTHREAD_THREADMASK */ +/* #undef HAVE_PTHREAD_YIELD_NP */ +/* #undef HAVE_READDIR_R */ +/* #undef HAVE_READLINK */ +/* #undef HAVE_REALPATH */ +#define HAVE_RENAME 1 +/* #undef HAVE_RINT */ +/* #undef HAVE_SCHED_YIELD */ +/* #undef HAVE_SELECT */ +/* #undef HAVE_SETFD */ +/* #undef HAVE_SETFILEPOINTER */ +/* #undef HAVE_SIGACTION */ +/* #undef HAVE_SIGTHREADMASK */ +/* #undef HAVE_SIGWAIT */ +/* #undef HAVE_SLEEP */ +/* #undef HAVE_SNPRINTF */ +/* #undef HAVE_STPCPY */ +#define HAVE_STRERROR 1 +/* #undef HAVE_STRLCPY */ +#define HAVE_STRNLEN 1 +#define HAVE_STRPBRK 1 +/* #undef HAVE_STRSEP */ +#define HAVE_STRSTR 1 +/* #undef HAVE_STRTOK_R */ +/* #undef HAVE_STRTOK_R */ +#define HAVE_STRTOL 1 +/* #undef HAVE_STRTOLL */ +#define HAVE_STRTOUL 1 +/* #undef HAVE_STRTOULL */ +#define HAVE_TELL 1 +/* #undef HAVE_THR_SETCONCURRENCY */ +/* #undef HAVE_THR_YIELD */ +/* #undef HAVE_VASPRINTF */ +#define HAVE_VSNPRINTF 1 + +/* Symbols we may use */ +/* #undef HAVE_SYS_ERRLIST */ +/* used by stacktrace functions */ +/* #undef HAVE_BSS_START */ + +/* Does "struct timespec" have a "sec" and "nsec" field? */ +/* #undef HAVE_TIMESPEC_TS_SEC */ + +/* Types we may use */ +#define SIZEOF_CHAR 1 +#if SIZEOF_CHAR +# define HAVE_CHAR 1 +#endif + +#define SIZEOF_CHARP 4 +#if SIZEOF_CHARP +# define HAVE_CHARP 1 +#endif + +#define SIZEOF_SHORT 2 +#if SIZEOF_SHORT +# define HAVE_SHORT 1 +#endif + +#define SIZEOF_INT 4 +#if SIZEOF_INT +# define HAVE_INT 1 +#endif + +#define SIZEOF_LONG 4 +#if SIZEOF_LONG +# define HAVE_LONG 1 +#endif + +#define SIZEOF_LONG_LONG 8 +#if SIZEOF_LONG_LONG +# define HAVE_LONG_LONG 1 +#endif + +#define SIZEOF_OFF_T 4 +#if SIZEOF_OFF_T +# define HAVE_OFF_T 1 +#endif + +/* #undef SIZEOF_SIGSET_T */ +#if SIZEOF_SIGSET_T +# define HAVE_SIGSET_T 1 +#endif + +#define SIZEOF_SIZE_T 4 +#if SIZEOF_SIZE_T +# define HAVE_SIZE_T 1 +#endif + +/* #undef SIZEOF_UCHAR */ +#if SIZEOF_UCHAR +# define HAVE_UCHAR 1 +#endif + +/* #undef SIZEOF_UINT */ +#if SIZEOF_UINT +# define HAVE_UINT 1 +#endif + +/* #undef SIZEOF_ULONG */ +#if SIZEOF_ULONG +# define HAVE_ULONG 1 +#endif + +/* #undef SIZEOF_INT8 */ +#if SIZEOF_INT8 +# define HAVE_INT8 1 +#endif +/* #undef SIZEOF_UINT8 */ +#if SIZEOF_UINT8 +# define HAVE_UINT8 1 +#endif + +/* #undef SIZEOF_INT16 */ +#if SIZEOF_INT16 +# define HAVE_INT16 1 +#endif +/* #undef SIZEOF_UINT16 */ +#if SIZEOF_UINT16 +# define HAVE_UINT16 1 +#endif + +/* #undef SIZEOF_INT32 */ +#if SIZEOF_INT32 +# define HAVE_INT32 1 +#endif +/* #undef SIZEOF_UINT32 */ +#if SIZEOF_UINT32 +# define HAVE_UINT32 1 +#endif +/* #undef SIZEOF_U_INT32_T */ +#if SIZEOF_U_INT32_T +# define HAVE_U_INT32_T 1 +#endif + +/* #undef SIZEOF_INT64 */ +#if SIZEOF_INT64 +# define HAVE_INT64 1 +#endif +/* #undef SIZEOF_UINT64 */ +#if SIZEOF_UINT64 +# define HAVE_UINT64 1 +#endif + +/* #undef SIZEOF_SOCKLEN_T */ +#if SIZEOF_SOCKLEN_T +# define HAVE_SOCKLEN_T 1 +#endif + +/* XXX mysql_client_test uses this -- rip it out, please! */ +#define MAX_INDEXES 64 + +#define QSORT_TYPE_IS_VOID 1 +#define RETQSORTTYPE void + +#define SIGNAL_RETURN_TYPE_IS_VOID 1 +#define RETSIGTYPE void + +/* #undef WORDS_BIGENDIAN */ + +/* Define to `__inline__' or `__inline' if that's what the C compiler calls + it, or to nothing if 'inline' is not supported under any name. */ +#ifndef __cplusplus +# define inline +#endif + +#define TIME_WITH_SYS_TIME 1 + +#define STACK_DIRECTION -1 + +#define SHAREDIR "share" +#define THREAD 1 +#define THREAD_SAFE_CLIENT 1 + +#define DEFAULT_CHARSET_HOME "C:/mysql/" diff --git a/mysql_incl/my_dbug.h b/mysql_incl/my_dbug.h new file mode 100644 index 0000000..c4a2f88 --- /dev/null +++ b/mysql_incl/my_dbug.h @@ -0,0 +1,140 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _dbug_h +#define _dbug_h + +#ifdef __cplusplus +extern "C" { +#endif +#if !defined(DBUG_OFF) && !defined(_lint) + +struct _db_stack_frame_ { + const char *func; /* function name of the previous stack frame */ + const char *file; /* filename of the function of previous frame */ + uint level; /* this nesting level, highest bit enables tracing */ + struct _db_stack_frame_ *prev; /* pointer to the previous frame */ +}; + +struct _db_code_state_; +extern my_bool _dbug_on_; +extern my_bool _db_keyword_(struct _db_code_state_ *, const char *, int); +extern int _db_explain_(struct _db_code_state_ *cs, char *buf, size_t len); +extern int _db_explain_init_(char *buf, size_t len); +extern int _db_is_pushed_(void); +extern void _db_setjmp_(void); +extern void _db_longjmp_(void); +extern void _db_process_(const char *name); +extern void _db_push_(const char *control); +extern void _db_pop_(void); +extern void _db_set_(const char *control); +extern void _db_set_init_(const char *control); +extern void _db_enter_(const char *_func_, const char *_file_, uint _line_, + struct _db_stack_frame_ *_stack_frame_); +extern void _db_return_(uint _line_, struct _db_stack_frame_ *_stack_frame_); +extern void _db_pargs_(uint _line_,const char *keyword); +extern void _db_doprnt_ _VARARGS((const char *format,...)) + ATTRIBUTE_FORMAT(printf, 1, 2); +extern void _db_dump_(uint _line_,const char *keyword, + const unsigned char *memory, size_t length); +extern void _db_end_(void); +extern void _db_lock_file_(void); +extern void _db_unlock_file_(void); +extern FILE *_db_fp_(void); +extern void _db_flush_(); + +#define DBUG_ENTER(a) struct _db_stack_frame_ _db_stack_frame_; \ + _db_enter_ (a,__FILE__,__LINE__,&_db_stack_frame_) +#define DBUG_LEAVE _db_return_ (__LINE__, &_db_stack_frame_) +#define DBUG_RETURN(a1) do {DBUG_LEAVE; return(a1);} while(0) +#define DBUG_VOID_RETURN do {DBUG_LEAVE; return;} while(0) +#define DBUG_EXECUTE(keyword,a1) \ + do {if (_db_keyword_(0, (keyword), 0)) { a1 }} while(0) +#define DBUG_EXECUTE_IF(keyword,a1) \ + do {if (_db_keyword_(0, (keyword), 1)) { a1 }} while(0) +#define DBUG_EVALUATE(keyword,a1,a2) \ + (_db_keyword_(0,(keyword), 0) ? (a1) : (a2)) +#define DBUG_EVALUATE_IF(keyword,a1,a2) \ + (_db_keyword_(0,(keyword), 1) ? (a1) : (a2)) +#define DBUG_PRINT(keyword,arglist) \ + do {_db_pargs_(__LINE__,keyword); _db_doprnt_ arglist;} while(0) +#define DBUG_PUSH(a1) _db_push_ (a1) +#define DBUG_POP() _db_pop_ () +#define DBUG_SET(a1) _db_set_ (a1) +#define DBUG_SET_INITIAL(a1) _db_set_init_ (a1) +#define DBUG_PROCESS(a1) _db_process_(a1) +#define DBUG_FILE _db_fp_() +#define DBUG_SETJMP(a1) (_db_setjmp_ (), setjmp (a1)) +#define DBUG_LONGJMP(a1,a2) (_db_longjmp_ (), longjmp (a1, a2)) +#define DBUG_DUMP(keyword,a1,a2) _db_dump_(__LINE__,keyword,a1,a2) +#define DBUG_END() _db_end_ () +#define DBUG_LOCK_FILE _db_lock_file_() +#define DBUG_UNLOCK_FILE _db_unlock_file_() +#define DBUG_ASSERT(A) assert(A) +#define DBUG_EXPLAIN(buf,len) _db_explain_(0, (buf),(len)) +#define DBUG_EXPLAIN_INITIAL(buf,len) _db_explain_init_((buf),(len)) +#define DEBUGGER_OFF do { _dbug_on_= 0; } while(0) +#define DEBUGGER_ON do { _dbug_on_= 1; } while(0) +#define IF_DBUG(A) A +#ifndef __WIN__ +#define DBUG_ABORT() (_db_flush_(), abort()) +#else +/* + Avoid popup with abort/retry/ignore buttons. When BUG#31745 is fixed we can + call abort() instead of _exit(3) (now it would cause a "test signal" popup). +*/ +#include +#define DBUG_ABORT() (_db_flush_(),\ + (void)_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE),\ + (void)_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR),\ + _exit(3)) +#endif + +#else /* No debugger */ + +#define DBUG_ENTER(a1) +#define DBUG_LEAVE +#define DBUG_RETURN(a1) do { return(a1); } while(0) +#define DBUG_VOID_RETURN do { return; } while(0) +#define DBUG_EXECUTE(keyword,a1) do { } while(0) +#define DBUG_EXECUTE_IF(keyword,a1) do { } while(0) +#define DBUG_EVALUATE(keyword,a1,a2) (a2) +#define DBUG_EVALUATE_IF(keyword,a1,a2) (a2) +#define DBUG_PRINT(keyword,arglist) do { } while(0) +#define DBUG_PUSH(a1) do { } while(0) +#define DBUG_SET(a1) do { } while(0) +#define DBUG_SET_INITIAL(a1) do { } while(0) +#define DBUG_POP() do { } while(0) +#define DBUG_PROCESS(a1) do { } while(0) +#define DBUG_SETJMP(a1) setjmp(a1) +#define DBUG_LONGJMP(a1) longjmp(a1) +#define DBUG_DUMP(keyword,a1,a2) do { } while(0) +#define DBUG_END() do { } while(0) +#define DBUG_ASSERT(A) do { } while(0) +#define DBUG_LOCK_FILE do { } while(0) +#define DBUG_FILE (stderr) +#define DBUG_UNLOCK_FILE do { } while(0) +#define DBUG_EXPLAIN(buf,len) +#define DBUG_EXPLAIN_INITIAL(buf,len) +#define DEBUGGER_OFF do { } while(0) +#define DEBUGGER_ON do { } while(0) +#define IF_DBUG(A) +#define DBUG_ABORT() abort() + +#endif +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/my_dir.h b/mysql_incl/my_dir.h new file mode 100644 index 0000000..90d708a --- /dev/null +++ b/mysql_incl/my_dir.h @@ -0,0 +1,109 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _my_dir_h +#define _my_dir_h +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef MY_DIR_H +#define MY_DIR_H + +#include + + /* Defines for my_dir and my_stat */ + +#define MY_S_IFMT S_IFMT /* type of file */ +#define MY_S_IFDIR S_IFDIR /* directory */ +#define MY_S_IFCHR S_IFCHR /* character special */ +#define MY_S_IFBLK S_IFBLK /* block special */ +#define MY_S_IFREG S_IFREG /* regular */ +#define MY_S_IFIFO S_IFIFO /* fifo */ +#define MY_S_ISUID S_ISUID /* set user id on execution */ +#define MY_S_ISGID S_ISGID /* set group id on execution */ +#define MY_S_ISVTX S_ISVTX /* save swapped text even after use */ +#define MY_S_IREAD S_IREAD /* read permission, owner */ +#define MY_S_IWRITE S_IWRITE /* write permission, owner */ +#define MY_S_IEXEC S_IEXEC /* execute/search permission, owner */ + +#define MY_S_ISDIR(m) (((m) & MY_S_IFMT) == MY_S_IFDIR) +#define MY_S_ISCHR(m) (((m) & MY_S_IFMT) == MY_S_IFCHR) +#define MY_S_ISBLK(m) (((m) & MY_S_IFMT) == MY_S_IFBLK) +#define MY_S_ISREG(m) (((m) & MY_S_IFMT) == MY_S_IFREG) +#define MY_S_ISFIFO(m) (((m) & MY_S_IFMT) == MY_S_IFIFO) + +#define MY_DONT_SORT 512 /* my_lib; Don't sort files */ +#define MY_WANT_STAT 1024 /* my_lib; stat files */ + + /* typedefs for my_dir & my_stat */ + +#ifdef USE_MY_STAT_STRUCT + +typedef struct my_stat +{ + dev_t st_dev; /* major & minor device numbers */ + ino_t st_ino; /* inode number */ + ushort st_mode; /* file permissons (& suid sgid .. bits) */ + short st_nlink; /* number of links to file */ + ushort st_uid; /* user id */ + ushort st_gid; /* group id */ + dev_t st_rdev; /* more major & minor device numbers (???) */ + off_t st_size; /* size of file */ + time_t st_atime; /* time for last read */ + time_t st_mtime; /* time for last contens modify */ + time_t st_ctime; /* time for last inode or contents modify */ +} MY_STAT; + +#else + +#if(_MSC_VER) +#define MY_STAT struct _stati64 /* 64 bit file size */ +#else +#define MY_STAT struct stat /* Orginal struct have what we need */ +#endif + +#endif /* USE_MY_STAT_STRUCT */ + +/* Struct describing one file returned from my_dir */ +typedef struct fileinfo +{ + char *name; + MY_STAT *mystat; +} FILEINFO; + +typedef struct st_my_dir /* Struct returned from my_dir */ +{ + /* + These members are just copies of parts of DYNAMIC_ARRAY structure, + which is allocated right after the end of MY_DIR structure (MEM_ROOT + for storing names is also resides there). We've left them here because + we don't want to change code that uses my_dir. + */ + struct fileinfo *dir_entry; + uint number_off_files; +} MY_DIR; + +extern MY_DIR *my_dir(const char *path,myf MyFlags); +extern void my_dirend(MY_DIR *buffer); +extern MY_STAT *my_stat(const char *path, MY_STAT *stat_area, myf my_flags); +extern int my_fstat(int filenr, MY_STAT *stat_area, myf MyFlags); + +#endif /* MY_DIR_H */ + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/my_getopt.h b/mysql_incl/my_getopt.h new file mode 100644 index 0000000..7cbad60 --- /dev/null +++ b/mysql_incl/my_getopt.h @@ -0,0 +1,86 @@ +/* Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _my_getopt_h +#define _my_getopt_h + +C_MODE_START + +#define GET_NO_ARG 1 +#define GET_BOOL 2 +#define GET_INT 3 +#define GET_UINT 4 +#define GET_LONG 5 +#define GET_ULONG 6 +#define GET_LL 7 +#define GET_ULL 8 +#define GET_STR 9 +#define GET_STR_ALLOC 10 +#define GET_DISABLED 11 +#define GET_ENUM 12 +#define GET_SET 13 +#define GET_DOUBLE 14 + +#define GET_ASK_ADDR 128 +#define GET_TYPE_MASK 127 + +enum get_opt_arg_type { NO_ARG, OPT_ARG, REQUIRED_ARG }; + +struct st_typelib; + +struct my_option +{ + const char *name; /* Name of the option */ + int id; /* unique id or short option */ + const char *comment; /* option comment, for autom. --help */ + uchar **value; /* The variable value */ + uchar **u_max_value; /* The user def. max variable value */ + struct st_typelib *typelib; /* Pointer to possible values */ + ulong var_type; + enum get_opt_arg_type arg_type; + longlong def_value; /* Default value */ + longlong min_value; /* Min allowed value */ + longlong max_value; /* Max allowed value */ + longlong sub_size; /* Subtract this from given value */ + long block_size; /* Value should be a mult. of this */ + void *app_type; /* To be used by an application */ +}; + +typedef my_bool (* my_get_one_option) (int, const struct my_option *, char * ); +typedef void (* my_error_reporter) (enum loglevel level, const char *format, ... ); + +extern char *disabled_my_option; +extern my_bool my_getopt_print_errors; +extern my_bool my_getopt_skip_unknown; +extern my_error_reporter my_getopt_error_reporter; + +extern int handle_options (int *argc, char ***argv, + const struct my_option *longopts, my_get_one_option); +extern void my_cleanup_options(const struct my_option *options); +extern void my_print_help(const struct my_option *options); +extern void my_print_variables(const struct my_option *options); +extern void my_getopt_register_get_addr(uchar ** (*func_addr)(const char *, uint, + const struct my_option *, int *)); + +ulonglong getopt_ull_limit_value(ulonglong num, const struct my_option *optp, + my_bool *fix); +longlong getopt_ll_limit_value(longlong, const struct my_option *, + my_bool *fix); +my_bool getopt_compare_strings(const char *s, const char *t, uint length); + +C_MODE_END + +#endif /* _my_getopt_h */ + diff --git a/mysql_incl/my_global.h b/mysql_incl/my_global.h new file mode 100644 index 0000000..131507c --- /dev/null +++ b/mysql_incl/my_global.h @@ -0,0 +1,1616 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* This is the include file that should be included 'first' in every C file. */ + +#ifndef _global_h +#define _global_h + +/* + InnoDB depends on some MySQL internals which other plugins should not + need. This is because of InnoDB's foreign key support, "safe" binlog + truncation, and other similar legacy features. + + We define accessors for these internals unconditionally, but do not + expose them in mysql/plugin.h. They are declared in ha_innodb.h for + InnoDB's use. +*/ +#define INNODB_COMPATIBILITY_HOOKS + +#ifdef __CYGWIN__ +/* We use a Unix API, so pretend it's not Windows */ +#undef WIN +#undef WIN32 +#undef _WIN +#undef _WIN32 +#undef _WIN64 +#undef __WIN__ +#undef __WIN32__ +#define HAVE_ERRNO_AS_DEFINE +#endif /* __CYGWIN__ */ + +#if defined(__QNXNTO__) && !defined(FD_SETSIZE) +#define FD_SETSIZE 1024 /* Max number of file descriptor bits in + fd_set, used when calling 'select' + Must be defined before including + "sys/select.h" and "sys/time.h" + */ +#endif + + +/* to make command line shorter we'll define USE_PRAGMA_INTERFACE here */ +#ifdef USE_PRAGMA_IMPLEMENTATION +#define USE_PRAGMA_INTERFACE +#endif + +#if defined(i386) && !defined(__i386__) +#define __i386__ +#endif + +/* Macros to make switching between C and C++ mode easier */ +#ifdef __cplusplus +#define C_MODE_START extern "C" { +#define C_MODE_END } +#define STATIC_CAST(TYPE) static_cast +#else +#define C_MODE_START +#define C_MODE_END +#define STATIC_CAST(TYPE) (TYPE) +#endif + +#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32) +#include +#else +#include +#if defined(__cplusplus) && defined(inline) +#undef inline /* fix configure problem */ +#endif +#endif /* _WIN32... */ + +#include + +/* Make it easier to add conditional code for windows */ +#ifdef __WIN__ +#define IF_WIN(A,B) (A) +#else +#define IF_WIN(A,B) (B) +#endif + +#ifndef EMBEDDED_LIBRARY +#ifdef WITH_NDB_BINLOG +#define HAVE_NDB_BINLOG 1 +#endif +#endif /* !EMBEDDED_LIBRARY */ + +#ifndef EMBEDDED_LIBRARY +#define HAVE_REPLICATION +#define HAVE_EXTERNAL_CLIENT +#endif + +/* Some defines to avoid ifdefs in the code */ +#ifndef NETWARE_YIELD +#define NETWARE_YIELD +#define NETWARE_SET_SCREEN_MODE(A) +#endif + +/* Workaround for _LARGE_FILES and _LARGE_FILE_API incompatibility on AIX */ +#if defined(_AIX) && defined(_LARGE_FILE_API) +#undef _LARGE_FILE_API +#endif + +/* + The macros below are used to allow build of Universal/fat binaries of + MySQL and MySQL applications under darwin. +*/ +#if defined(__APPLE__) && defined(__MACH__) +# undef SIZEOF_CHARP +# undef SIZEOF_SHORT +# undef SIZEOF_INT +# undef SIZEOF_LONG +# undef SIZEOF_LONG_LONG +# undef SIZEOF_OFF_T +# undef WORDS_BIGENDIAN +# define SIZEOF_SHORT 2 +# define SIZEOF_INT 4 +# define SIZEOF_LONG_LONG 8 +# define SIZEOF_OFF_T 8 +# if defined(__i386__) || defined(__ppc__) +# define SIZEOF_CHARP 4 +# define SIZEOF_LONG 4 +# elif defined(__x86_64__) || defined(__ppc64__) +# define SIZEOF_CHARP 8 +# define SIZEOF_LONG 8 +# else +# error Building FAT binary for an unknown architecture. +# endif +# if defined(__ppc__) || defined(__ppc64__) +# define WORDS_BIGENDIAN +# endif +#endif /* defined(__APPLE__) && defined(__MACH__) */ + + +/* + The macros below are borrowed from include/linux/compiler.h in the + Linux kernel. Use them to indicate the likelyhood of the truthfulness + of a condition. This serves two purposes - newer versions of gcc will be + able to optimize for branch predication, which could yield siginficant + performance gains in frequently executed sections of the code, and the + other reason to use them is for documentation +*/ + +#if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96) +#define __builtin_expect(x, expected_value) (x) +#endif + +/** + The semantics of builtin_expect() are that + 1) its two arguments are long + 2) it's likely that they are == + Those of our likely(x) are that x can be bool/int/longlong/pointer. +*/ +#define likely(x) __builtin_expect(((x) != 0),1) +#define unlikely(x) __builtin_expect(((x) != 0),0) + +/* + The macros below are useful in optimising places where it has been + discovered that cache misses stall the process and where a prefetch + of the cache line can improve matters. This is available in GCC 3.1.1 + and later versions. + PREFETCH_READ says that addr is going to be used for reading and that + it is to be kept in caches if possible for a while + PREFETCH_WRITE also says that the item to be cached is likely to be + updated. + The *LOCALITY scripts are also available for experimentation purposes + mostly and should only be used if they are verified to improve matters. + For more input see GCC manual (available in GCC 3.1.1 and later) +*/ + +#if (__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR > 10) +#define PREFETCH_READ(addr) __builtin_prefetch(addr, 0, 3) +#define PREFETCH_WRITE(addr) \ + __builtin_prefetch(addr, 1, 3) +#define PREFETCH_READ_LOCALITY(addr, locality) \ + __builtin_prefetch(addr, 0, locality) +#define PREFETCH_WRITE_LOCALITY(addr, locality) \ + __builtin_prefetch(addr, 1, locality) +#else +#define PREFETCH_READ(addr) +#define PREFETCH_READ_LOCALITY(addr, locality) +#define PREFETCH_WRITE(addr) +#define PREFETCH_WRITE_LOCALITY(addr, locality) +#endif + +/* + The following macro is used to ensure that code often used in most + SQL statements and definitely for parts of the SQL processing are + kept in a code segment by itself. This has the advantage that the + risk of common code being overlapping in caches of the CPU is less. + This can be a cause of big performance problems. + Routines should be put in this category with care and when they are + put there one should also strive to make as much of the error handling + as possible (or uncommon code of the routine) to execute in a + separate method to avoid moving to much code to this code segment. + + It is very easy to use, simply add HOT_METHOD at the end of the + function declaration. + For more input see GCC manual (available in GCC 2.95 and later) +*/ + +#if (__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR > 94) +#define HOT_METHOD \ + __attribute__ ((section ("hot_code_section"))) +#else +#define HOT_METHOD +#endif + +/* + The following macro is used to ensure that popular global variables + are located next to each other to avoid that they contend for the + same cache lines. + + It is very easy to use, simply add HOT_DATA at the end of the declaration + of the variable, the variable must be initialised because of the way + that linker works so a declaration using HOT_DATA should look like: + uint global_hot_data HOT_DATA = 0; + For more input see GCC manual (available in GCC 2.95 and later) +*/ + +#if (__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR > 94) +#define HOT_DATA \ + __attribute__ ((section ("hot_data_section"))) +#else +#define HOT_DATA +#endif + +/* + now let's figure out if inline functions are supported + autoconf defines 'inline' to be empty, if not +*/ +#define inline_test_1(X) X ## 1 +#define inline_test_2(X) inline_test_1(X) +#if inline_test_2(inline) != 1 +#define HAVE_INLINE +#endif +#undef inline_test_2 +#undef inline_test_1 +/* helper macro for "instantiating" inline functions */ +#define STATIC_INLINE static inline + +/* + The following macros are used to control inlining a bit more than + usual. These macros are used to ensure that inlining always or + never occurs (independent of compilation mode). + For more input see GCC manual (available in GCC 3.1.1 and later) +*/ + +#if (__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR > 10) +#define ALWAYS_INLINE __attribute__ ((always_inline)) +#define NEVER_INLINE __attribute__ ((noinline)) +#else +#define ALWAYS_INLINE +#define NEVER_INLINE +#endif + + +/* Fix problem with S_ISLNK() on Linux */ +#if defined(TARGET_OS_LINUX) || defined(__GLIBC__) +#undef _GNU_SOURCE +#define _GNU_SOURCE 1 +#endif + +/* + Temporary solution to solve bug#7156. Include "sys/types.h" before + the thread headers, else the function madvise() will not be defined +*/ +#if defined(HAVE_SYS_TYPES_H) && ( defined(sun) || defined(__sun) ) +#include +#endif + +/* The client defines this to avoid all thread code */ +#if defined(UNDEF_THREADS_HACK) +#undef THREAD +#undef HAVE_LINUXTHREADS +#undef HAVE_NPTL +#endif + +#ifdef HAVE_THREADS_WITHOUT_SOCKETS +/* MIT pthreads does not work with unix sockets */ +#undef HAVE_SYS_UN_H +#endif + +#define __EXTENSIONS__ 1 /* We want some extension */ +#ifndef __STDC_EXT__ +#define __STDC_EXT__ 1 /* To get large file support on hpux */ +#endif + +/* + Solaris 9 include file refers to X/Open document + + System Interfaces and Headers, Issue 5 + + saying we should define _XOPEN_SOURCE=500 to get POSIX.1c prototypes, + but apparently other systems (namely FreeBSD) don't agree. + + On a newer Solaris 10, the above file recognizes also _XOPEN_SOURCE=600. + Furthermore, it tests that if a program requires older standard + (_XOPEN_SOURCE<600 or _POSIX_C_SOURCE<200112L) it cannot be + run on a new compiler (that defines _STDC_C99) and issues an #error. + It's also an #error if a program requires new standard (_XOPEN_SOURCE=600 + or _POSIX_C_SOURCE=200112L) and a compiler does not define _STDC_C99. + + To add more to this mess, Sun Studio C compiler defines _STDC_C99 while + C++ compiler does not! + + So, in a desperate attempt to get correct prototypes for both + C and C++ code, we define either _XOPEN_SOURCE=600 or _XOPEN_SOURCE=500 + depending on the compiler's announced C standard support. + + Cleaner solutions are welcome. +*/ +#ifdef __sun +#if __STDC_VERSION__ - 0 >= 199901L +#define _XOPEN_SOURCE 600 +#else +#define _XOPEN_SOURCE 500 +#endif +#endif + +#if defined(THREAD) && !defined(__WIN__) +#ifndef _POSIX_PTHREAD_SEMANTICS +#define _POSIX_PTHREAD_SEMANTICS /* We want posix threads */ +#endif + +#if !defined(SCO) +#define _REENTRANT 1 /* Some thread libraries require this */ +#endif +#if !defined(_THREAD_SAFE) && !defined(_AIX) +#define _THREAD_SAFE /* Required for OSF1 */ +#endif +#if defined(HPUX10) || defined(HPUX11) +C_MODE_START /* HPUX needs this, signal.h bug */ +#include +C_MODE_END +#else +#include /* AIX must have this included first */ +#endif +#if !defined(SCO) && !defined(_REENTRANT) +#define _REENTRANT 1 /* Threads requires reentrant code */ +#endif +#endif /* THREAD */ + +/* Go around some bugs in different OS and compilers */ +#ifdef _AIX /* By soren@t.dk */ +#define _H_STRINGS +#define _SYS_STREAM_H +/* #define _AIX32_CURSES */ /* XXX: this breaks AIX 4.3.3 (others?). */ +#define ulonglong2double(A) my_ulonglong2double(A) +#define my_off_t2double(A) my_ulonglong2double(A) +C_MODE_START +double my_ulonglong2double(unsigned long long A); +C_MODE_END +#endif /* _AIX */ + +#ifdef HAVE_BROKEN_SNPRINTF /* HPUX 10.20 don't have this defined */ +#undef HAVE_SNPRINTF +#endif +#ifdef HAVE_BROKEN_PREAD +/* + pread()/pwrite() are not 64 bit safe on HP-UX 11.0 without + installing the kernel patch PHKL_20349 or greater +*/ +#undef HAVE_PREAD +#undef HAVE_PWRITE +#endif +#if defined(HAVE_BROKEN_INLINE) && !defined(__cplusplus) +#undef inline +#define inline +#endif + +#ifdef UNDEF_HAVE_GETHOSTBYNAME_R /* For OSF4.x */ +#undef HAVE_GETHOSTBYNAME_R +#endif +#ifdef UNDEF_HAVE_INITGROUPS /* For AIX 4.3 */ +#undef HAVE_INITGROUPS +#endif + +/* gcc/egcs issues */ + +#if defined(__GNUC) && defined(__EXCEPTIONS) +#error "Please add -fno-exceptions to CXXFLAGS and reconfigure/recompile" +#endif + + +/* Fix a bug in gcc 2.8.0 on IRIX 6.2 */ +#if SIZEOF_LONG == 4 && defined(__LONG_MAX__) && (__GNUC__ == 2 && __GNUC_MINOR__ == 8) +#undef __LONG_MAX__ /* Is a longlong value in gcc 2.8.0 ??? */ +#define __LONG_MAX__ 2147483647 +#endif + +/* egcs 1.1.2 has a problem with memcpy on Alpha */ +#if defined(__GNUC__) && defined(__alpha__) && ! (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)) +#define BAD_MEMCPY +#endif + +#if defined(_lint) && !defined(lint) +#define lint +#endif +#if SIZEOF_LONG_LONG > 4 && !defined(_LONG_LONG) +#define _LONG_LONG 1 /* For AIX string library */ +#endif + +#ifndef stdin +#include +#endif +#include +#ifdef HAVE_STDLIB_H +#include +#endif +#ifdef HAVE_STDDEF_H +#include +#endif + +#include +#ifdef HAVE_LIMITS_H +#include +#endif +#ifdef HAVE_FLOAT_H +#include +#endif +#ifdef HAVE_FENV_H +#include /* For fesetround() */ +#endif + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#ifdef HAVE_SYS_TIMEB_H +#include /* Avoid warnings on SCO */ +#endif +#if TIME_WITH_SYS_TIME +# include +# include +#else +# if HAVE_SYS_TIME_H +# include +# else +# include +# endif +#endif /* TIME_WITH_SYS_TIME */ +#ifdef HAVE_UNISTD_H +#include +#endif +#if defined(__cplusplus) && defined(NO_CPLUSPLUS_ALLOCA) +#undef HAVE_ALLOCA +#undef HAVE_ALLOCA_H +#endif +#ifdef HAVE_ALLOCA_H +#include +#endif + +#include /* Recommended by debian */ +/* We need the following to go around a problem with openssl on solaris */ +#if defined(HAVE_CRYPT_H) +#include +#endif + +/* + A lot of our programs uses asserts, so better to always include it + This also fixes a problem when people uses DBUG_ASSERT without including + assert.h +*/ +#include + +/* an assert that works at compile-time. only for constant expression */ +#ifdef _some_old_compiler_that_does_not_understand_the_construct_below_ +#define compile_time_assert(X) do { } while(0) +#else +#define compile_time_assert(X) \ + do \ + { \ + typedef char compile_time_assert[(X) ? 1 : -1]; \ + } while(0) +#endif + +/* Go around some bugs in different OS and compilers */ +#if defined (HPUX11) && defined(_LARGEFILE_SOURCE) +#define _LARGEFILE64_SOURCE +#endif +#if defined(_HPUX_SOURCE) && defined(HAVE_SYS_STREAM_H) +#include /* HPUX 10.20 defines ulong here. UGLY !!! */ +#define HAVE_ULONG +#endif +#if defined(HPUX10) && defined(_LARGEFILE64_SOURCE) && defined(THREAD) +/* Fix bug in setrlimit */ +#undef setrlimit +#define setrlimit cma_setrlimit64 +#endif +/* Declare madvise where it is not declared for C++, like Solaris */ +#if HAVE_MADVISE && !HAVE_DECL_MADVISE && defined(__cplusplus) +extern "C" int madvise(void *addr, size_t len, int behav); +#endif + +#ifdef __QNXNTO__ +/* This has to be after include limits.h */ +#define HAVE_ERRNO_AS_DEFINE +#define HAVE_FCNTL_LOCK +#undef HAVE_FINITE +#undef LONGLONG_MIN /* These get wrongly defined in QNX 6.2 */ +#undef LONGLONG_MAX /* standard system library 'limits.h' */ +#endif + +/* We can not live without the following defines */ + +#define USE_MYFUNC 1 /* Must use syscall indirection */ +#define MASTER 1 /* Compile without unireg */ +#define ENGLISH 1 /* Messages in English */ +#define POSIX_MISTAKE 1 /* regexp: Fix stupid spec error */ +#define USE_REGEX 1 /* We want the use the regex library */ +/* Do not define for ultra sparcs */ +#define USE_BMOVE512 1 /* Use this unless system bmove is faster */ + +#define QUOTE_ARG(x) #x /* Quote argument (before cpp) */ +#define STRINGIFY_ARG(x) QUOTE_ARG(x) /* Quote argument, after cpp */ + +/* Paranoid settings. Define I_AM_PARANOID if you are paranoid */ +#ifdef I_AM_PARANOID +#define DONT_ALLOW_USER_CHANGE 1 +#define DONT_USE_MYSQL_PWD 1 +#endif + +/* Does the system remember a signal handler after a signal ? */ +#ifndef HAVE_BSD_SIGNALS +#define DONT_REMEMBER_SIGNAL +#endif + +#if defined(_lint) || defined(FORCE_INIT_OF_VARS) +#define LINT_INIT(var) var=0 /* No uninitialize-warning */ +#else +#define LINT_INIT(var) +#endif + +#if defined(_lint) || defined(FORCE_INIT_OF_VARS) || defined(HAVE_purify) +#define PURIFY_OR_LINT_INIT(var) var=0 +#else +#define PURIFY_OR_LINT_INIT(var) +#endif + +#if !defined(HAVE_UINT) +#undef HAVE_UINT +#define HAVE_UINT +typedef unsigned int uint; +typedef unsigned short ushort; +#endif + +#define CMP_NUM(a,b) (((a) < (b)) ? -1 : ((a) == (b)) ? 0 : 1) +#define sgn(a) (((a) < 0) ? -1 : ((a) > 0) ? 1 : 0) +#define swap_variables(t, a, b) { t swap_dummy; swap_dummy= a; a= b; b= swap_dummy; } +#define test(a) ((a) ? 1 : 0) +#define set_if_bigger(a,b) do { if ((a) < (b)) (a)=(b); } while(0) +#define set_if_smaller(a,b) do { if ((a) > (b)) (a)=(b); } while(0) +#define test_all_bits(a,b) (((a) & (b)) == (b)) +#define set_bits(type, bit_count) (sizeof(type)*8 <= (bit_count) ? ~(type) 0 : ((((type) 1) << (bit_count)) - (type) 1)) +#define array_elements(A) ((uint) (sizeof(A)/sizeof(A[0]))) + +/* Define some general constants */ +#ifndef TRUE +#define TRUE (1) /* Logical true */ +#define FALSE (0) /* Logical false */ +#endif + +#if defined(__GNUC__) +#define function_volatile volatile +#define my_reinterpret_cast(A) reinterpret_cast +#define my_const_cast(A) const_cast +# ifndef GCC_VERSION +# define GCC_VERSION (__GNUC__ * 1000 + __GNUC_MINOR__) +# endif +#elif !defined(my_reinterpret_cast) +#define my_reinterpret_cast(A) (A) +#define my_const_cast(A) (A) +#endif + +#include + +/* + Wen using the embedded library, users might run into link problems, + duplicate declaration of __cxa_pure_virtual, solved by declaring it a + weak symbol. +*/ +#if defined(USE_MYSYS_NEW) && ! defined(DONT_DECLARE_CXA_PURE_VIRTUAL) +C_MODE_START +int __cxa_pure_virtual () __attribute__ ((weak)); +C_MODE_END +#endif + +/* From old s-system.h */ + +/* + Support macros for non ansi & other old compilers. Since such + things are no longer supported we do nothing. We keep then since + some of our code may still be needed to upgrade old customers. +*/ +#define _VARARGS(X) X +#define _STATIC_VARARGS(X) X + +/* The DBUG_ON flag always takes precedence over default DBUG_OFF */ +#if defined(DBUG_ON) && defined(DBUG_OFF) +#undef DBUG_OFF +#endif + +/* We might be forced to turn debug off, if not turned off already */ +#if (defined(FORCE_DBUG_OFF) || defined(_lint)) && !defined(DBUG_OFF) +# define DBUG_OFF +# ifdef DBUG_ON +# undef DBUG_ON +# endif +#endif + +typedef char my_bool; /* Small bool */ +#include + +#define MIN_ARRAY_SIZE 0 /* Zero or One. Gcc allows zero*/ +#define ASCII_BITS_USED 8 /* Bit char used */ +#define NEAR_F /* No near function handling */ + +/* Some types that is different between systems */ + +typedef int File; /* File descriptor */ +#ifndef Socket_defined +typedef int my_socket; /* File descriptor for sockets */ +#define INVALID_SOCKET -1 +#endif +/* Type for fuctions that handles signals */ +#define sig_handler void +C_MODE_START +typedef void (*sig_return)();/* Returns type from signal */ +C_MODE_END +#if defined(__GNUC__) && !defined(_lint) +typedef char pchar; /* Mixed prototypes can take char */ +typedef char puchar; /* Mixed prototypes can take char */ +typedef char pbool; /* Mixed prototypes can take char */ +typedef short pshort; /* Mixed prototypes can take short int */ +typedef float pfloat; /* Mixed prototypes can take float */ +#else +typedef int pchar; /* Mixed prototypes can't take char */ +typedef uint puchar; /* Mixed prototypes can't take char */ +typedef int pbool; /* Mixed prototypes can't take char */ +typedef int pshort; /* Mixed prototypes can't take short int */ +typedef double pfloat; /* Mixed prototypes can't take float */ +#endif +C_MODE_START +typedef int (*qsort_cmp)(const void *,const void *); +typedef int (*qsort_cmp2)(void*, const void *,const void *); +C_MODE_END +#define qsort_t RETQSORTTYPE /* Broken GCC cant handle typedef !!!! */ +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + +/* file create flags */ + +#ifndef O_SHARE /* Probably not windows */ +#define O_SHARE 0 /* Flag to my_open for shared files */ +#ifndef O_BINARY +#define O_BINARY 0 /* Flag to my_open for binary files */ +#endif +#ifndef FILE_BINARY +#define FILE_BINARY O_BINARY /* Flag to my_fopen for binary streams */ +#endif +#ifdef HAVE_FCNTL +#define HAVE_FCNTL_LOCK +#define F_TO_EOF 0L /* Param to lockf() to lock rest of file */ +#endif +#endif /* O_SHARE */ + +#ifndef O_TEMPORARY +#define O_TEMPORARY 0 +#endif +#ifndef O_SHORT_LIVED +#define O_SHORT_LIVED 0 +#endif +#ifndef O_NOFOLLOW +#define O_NOFOLLOW 0 +#endif + +/* additional file share flags for win32 */ +#ifdef __WIN__ +#define _SH_DENYRWD 0x110 /* deny read/write mode & delete */ +#define _SH_DENYWRD 0x120 /* deny write mode & delete */ +#define _SH_DENYRDD 0x130 /* deny read mode & delete */ +#define _SH_DENYDEL 0x140 /* deny delete only */ +#endif /* __WIN__ */ + + +/* #define USE_RECORD_LOCK */ + + /* Unsigned types supported by the compiler */ +#define UNSINT8 /* unsigned int8 (char) */ +#define UNSINT16 /* unsigned int16 */ +#define UNSINT32 /* unsigned int32 */ + + /* General constants */ +#define FN_LEN 256 /* Max file name len */ +#define FN_HEADLEN 253 /* Max length of filepart of file name */ +#define FN_EXTLEN 20 /* Max length of extension (part of FN_LEN) */ +#define FN_REFLEN 512 /* Max length of full path-name */ +#define FN_EXTCHAR '.' +#define FN_HOMELIB '~' /* ~/ is used as abbrev for home dir */ +#define FN_CURLIB '.' /* ./ is used as abbrev for current dir */ +#define FN_PARENTDIR ".." /* Parent directory; Must be a string */ + +#ifndef FN_LIBCHAR +#define FN_LIBCHAR '/' +#define FN_ROOTDIR "/" +#endif + +/* + MY_FILE_MIN is Windows speciality and is used to quickly detect + the mismatch of CRT and mysys file IO usage on Windows at runtime. + CRT file descriptors can be in the range 0-2047, whereas descriptors returned + by my_open() will start with 2048. If a file descriptor with value less then + MY_FILE_MIN is passed to mysys IO function, chances are it stemms from + open()/fileno() and not my_open()/my_fileno. + + For Posix, mysys functions are light wrappers around libc, and MY_FILE_MIN + is logically 0. +*/ + +#ifdef _WIN32 +#define MY_FILE_MIN 2048 +#else +#define MY_FILE_MIN 0 +#endif + +/* + MY_NFILE is the default size of my_file_info array. + + It is larger on Windows, because it all file handles are stored in my_file_info + Default size is 16384 and this should be enough for most cases.If it is not + enough, --max-open-files with larger value can be used. + + For Posix , my_file_info array is only used to store filenames for + error reporting and its size is not a limitation for number of open files. +*/ +#ifdef _WIN32 +#define MY_NFILE (16384 + MY_FILE_MIN) +#else +#define MY_NFILE 64 +#endif + +#ifndef OS_FILE_LIMIT +#define OS_FILE_LIMIT 65535 +#endif + +/* #define EXT_IN_LIBNAME */ +/* #define FN_NO_CASE_SENCE */ +/* #define FN_UPPER_CASE TRUE */ + +/* + Io buffer size; Must be a power of 2 and a multiple of 512. May be + smaller what the disk page size. This influences the speed of the + isam btree library. eg to big to slow. +*/ +#define IO_SIZE 4096 +/* + How much overhead does malloc have. The code often allocates + something like 1024-MALLOC_OVERHEAD bytes +*/ +#ifdef SAFEMALLOC +#define MALLOC_OVERHEAD (8+24+4) +#else +#define MALLOC_OVERHEAD 8 +#endif + /* get memory in huncs */ +#define ONCE_ALLOC_INIT (uint) (4096-MALLOC_OVERHEAD) + /* Typical record cash */ +#define RECORD_CACHE_SIZE (uint) (64*1024-MALLOC_OVERHEAD) + /* Typical key cash */ +#define KEY_CACHE_SIZE (uint) (8*1024*1024-MALLOC_OVERHEAD) + /* Default size of a key cache block */ +#define KEY_CACHE_BLOCK_SIZE (uint) 1024 + + + /* Some things that this system doesn't have */ + +#define NO_HASH /* Not needed anymore */ +#ifdef _WIN32 +#define NO_DIR_LIBRARY /* Not standard dir-library */ +#endif + +/* Some defines of functions for portability */ + +#undef remove /* Crashes MySQL on SCO 5.0.0 */ +#ifndef __WIN__ +#define closesocket(A) close(A) +#ifndef ulonglong2double +#define ulonglong2double(A) ((double) (ulonglong) (A)) +#define my_off_t2double(A) ((double) (my_off_t) (A)) +#endif +#ifndef double2ulonglong +#define double2ulonglong(A) ((ulonglong) (double) (A)) +#endif +#endif + +#ifndef offsetof +#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) +#endif +#define ulong_to_double(X) ((double) (ulong) (X)) +#define SET_STACK_SIZE(X) /* Not needed on real machines */ + +#ifndef STACK_DIRECTION +#error "please add -DSTACK_DIRECTION=1 or -1 to your CPPFLAGS" +#endif + +#if !defined(HAVE_STRTOK_R) +inline char *strtok_r(char *str, const char *delim, char **saveptr) +{ + return strtok(str,delim); +} +#endif + +/* This is from the old m-machine.h file */ + +#if SIZEOF_LONG_LONG > 4 +#define HAVE_LONG_LONG 1 +#endif + +/* + Some pre-ANSI-C99 systems like AIX 5.1 and Linux/GCC 2.95 define + ULONGLONG_MAX, LONGLONG_MIN, LONGLONG_MAX; we use them if they're defined. + Also on Windows we define these constants by hand in config-win.h. +*/ + +#if defined(HAVE_LONG_LONG) && !defined(LONGLONG_MIN) +#define LONGLONG_MIN ((long long) 0x8000000000000000LL) +#define LONGLONG_MAX ((long long) 0x7FFFFFFFFFFFFFFFLL) +#endif + +#if defined(HAVE_LONG_LONG) && !defined(ULONGLONG_MAX) +/* First check for ANSI C99 definition: */ +#ifdef ULLONG_MAX +#define ULONGLONG_MAX ULLONG_MAX +#else +#define ULONGLONG_MAX ((unsigned long long)(~0ULL)) +#endif +#endif /* defined (HAVE_LONG_LONG) && !defined(ULONGLONG_MAX)*/ + +#define INT_MIN32 (~0x7FFFFFFFL) +#define INT_MAX32 0x7FFFFFFFL +#define UINT_MAX32 0xFFFFFFFFL +#define INT_MIN24 (~0x007FFFFF) +#define INT_MAX24 0x007FFFFF +#define UINT_MAX24 0x00FFFFFF +#define INT_MIN16 (~0x7FFF) +#define INT_MAX16 0x7FFF +#define UINT_MAX16 0xFFFF +#define INT_MIN8 (~0x7F) +#define INT_MAX8 0x7F +#define UINT_MAX8 0xFF + +/* From limits.h instead */ +#ifndef DBL_MIN +#define DBL_MIN 4.94065645841246544e-324 +#define FLT_MIN ((float)1.40129846432481707e-45) +#endif +#ifndef DBL_MAX +#define DBL_MAX 1.79769313486231470e+308 +#define FLT_MAX ((float)3.40282346638528860e+38) +#endif +#ifndef SIZE_T_MAX +#define SIZE_T_MAX ~((size_t) 0) +#endif + +#ifndef isfinite +#ifdef HAVE_FINITE +#define isfinite(x) finite(x) +#else +#define finite(x) (1.0 / fabs(x) > 0.0) +#endif /* HAVE_FINITE */ +#endif /* isfinite */ + +#ifndef HAVE_ISNAN +#define isnan(x) ((x) != (x)) +#endif + +#ifdef HAVE_ISINF +/* Check if C compiler is affected by GCC bug #39228 */ +#if !defined(__cplusplus) && defined(HAVE_BROKEN_ISINF) +/* Force store/reload of the argument to/from a 64-bit double */ +static inline double my_isinf(double x) +{ + volatile double t= x; + return isinf(t); +} +#else +/* System-provided isinf() is available and safe to use */ +#define my_isinf(X) isinf(X) +#endif +#else /* !HAVE_ISINF */ +#define my_isinf(X) (!finite(X) && !isnan(X)) +#endif + +/* Define missing math constants. */ +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif +#ifndef M_E +#define M_E 2.7182818284590452354 +#endif +#ifndef M_LN2 +#define M_LN2 0.69314718055994530942 +#endif + +/* + Max size that must be added to a so that we know Size to make + adressable obj. +*/ +#if SIZEOF_CHARP == 4 +typedef long my_ptrdiff_t; +#else +typedef long long my_ptrdiff_t; +#endif + +#define MY_ALIGN(A,L) (((A) + (L) - 1) & ~((L) - 1)) +#define ALIGN_SIZE(A) MY_ALIGN((A),sizeof(double)) +/* Size to make adressable obj. */ +#define ALIGN_PTR(A, t) ((t*) MY_ALIGN((A),sizeof(t))) + /* Offset of field f in structure t */ +#define OFFSET(t, f) ((size_t)(char *)&((t *)0)->f) +#define ADD_TO_PTR(ptr,size,type) (type) ((uchar*) (ptr)+size) +#define PTR_BYTE_DIFF(A,B) (my_ptrdiff_t) ((uchar*) (A) - (uchar*) (B)) + +#define MY_DIV_UP(A, B) (((A) + (B) - 1) / (B)) +#define MY_ALIGNED_BYTE_ARRAY(N, S, T) T N[MY_DIV_UP(S, sizeof(T))] + +/* + Custom version of standard offsetof() macro which can be used to get + offsets of members in class for non-POD types (according to the current + version of C++ standard offsetof() macro can't be used in such cases and + attempt to do so causes warnings to be emitted, OTOH in many cases it is + still OK to assume that all instances of the class has the same offsets + for the same members). + + This is temporary solution which should be removed once File_parser class + and related routines are refactored. +*/ + +#define my_offsetof(TYPE, MEMBER) \ + ((size_t)((char *)&(((TYPE *)0x10)->MEMBER) - (char*)0x10)) + +#define NullS STATIC_CAST(char *)(0) +/* Nowdays we do not support MessyDos */ +#ifndef NEAR +#define NEAR /* Who needs segments ? */ +#define FAR /* On a good machine */ +#ifndef HUGE_PTR +#define HUGE_PTR +#endif +#endif +#if defined(__IBMC__) || defined(__IBMCPP__) +/* This was _System _Export but caused a lot of warnings on _AIX43 */ +#define STDCALL +#elif !defined( STDCALL) +#define STDCALL +#endif + +/* Typdefs for easyier portability */ + +#ifndef HAVE_UCHAR +typedef unsigned char uchar; /* Short for unsigned char */ +#endif + +#ifndef HAVE_INT8 +typedef signed char int8; /* Signed integer >= 8 bits */ +#endif +#ifndef HAVE_UINT8 +typedef unsigned char uint8; /* Unsigned integer >= 8 bits */ +#endif +#ifndef HAVE_INT16 +typedef short int16; +#endif +#ifndef HAVE_UINT16 +typedef unsigned short uint16; +#endif +#if SIZEOF_INT == 4 +#ifndef HAVE_INT32 +typedef int int32; +#endif +#ifndef HAVE_UINT32 +typedef unsigned int uint32; +#endif +#elif SIZEOF_LONG == 4 +#ifndef HAVE_INT32 +typedef long int32; +#endif +#ifndef HAVE_UINT32 +typedef unsigned long uint32; +#endif +#else +#error Neither int or long is of 4 bytes width +#endif + +#if !defined(HAVE_ULONG) && !defined(__USE_MISC) +typedef unsigned long ulong; /* Short for unsigned long */ +#endif +#ifndef longlong_defined +/* + Using [unsigned] long long is preferable as [u]longlong because we use + [unsigned] long long unconditionally in many places, + for example in constants with [U]LL suffix. +*/ +#if defined(HAVE_LONG_LONG) && SIZEOF_LONG_LONG == 8 +typedef unsigned long long int ulonglong; /* ulong or unsigned long long */ +typedef long long int longlong; +#else +typedef unsigned long ulonglong; /* ulong or unsigned long long */ +typedef long longlong; +#endif +#endif +#ifndef HAVE_INT64 +typedef longlong int64; +#endif +#ifndef HAVE_UINT64 +typedef ulonglong uint64; +#endif + +#if defined(NO_CLIENT_LONG_LONG) +typedef unsigned long my_ulonglong; +#elif defined (__WIN__) +typedef unsigned __int64 my_ulonglong; +#else +typedef unsigned long long my_ulonglong; +#endif + +#if SIZEOF_CHARP == SIZEOF_INT +typedef int intptr; +#elif SIZEOF_CHARP == SIZEOF_LONG +typedef long intptr; +#elif SIZEOF_CHARP == SIZEOF_LONG_LONG +typedef long long intptr; +#else +#error sizeof(void *) is neither sizeof(int) nor sizeof(long) nor sizeof(long long) +#endif + +#define MY_ERRPTR ((void*)(intptr)1) + +#ifdef USE_RAID +/* + The following is done with a if to not get problems with pre-processors + with late define evaluation +*/ +#if SIZEOF_OFF_T == 4 +#define SYSTEM_SIZEOF_OFF_T 4 +#else +#define SYSTEM_SIZEOF_OFF_T 8 +#endif +#undef SIZEOF_OFF_T +#define SIZEOF_OFF_T 8 +#else +#define SYSTEM_SIZEOF_OFF_T SIZEOF_OFF_T +#endif /* USE_RAID */ + +#if SIZEOF_OFF_T > 4 +typedef ulonglong my_off_t; +#else +typedef unsigned long my_off_t; +#endif +#define MY_FILEPOS_ERROR (~STATIC_CAST(my_off_t)(0)) +#if !defined(__WIN__) +typedef off_t os_off_t; +#endif + +#if defined(__WIN__) +#define socket_errno WSAGetLastError() +#define SOCKET_EINTR WSAEINTR +#define SOCKET_EAGAIN WSAEINPROGRESS +#define SOCKET_ETIMEDOUT WSAETIMEDOUT +#define SOCKET_EWOULDBLOCK WSAEWOULDBLOCK +#define SOCKET_EADDRINUSE WSAEADDRINUSE +#define SOCKET_ENFILE ENFILE +#define SOCKET_EMFILE EMFILE +#else /* Unix */ +#define socket_errno errno +#define closesocket(A) close(A) +#define SOCKET_EINTR EINTR +#define SOCKET_EAGAIN EAGAIN +#define SOCKET_ETIMEDOUT SOCKET_EINTR +#define SOCKET_EWOULDBLOCK EWOULDBLOCK +#define SOCKET_EADDRINUSE EADDRINUSE +#define SOCKET_ENFILE ENFILE +#define SOCKET_EMFILE EMFILE +#endif + +typedef uint8 int7; /* Most effective integer 0 <= x <= 127 */ +typedef short int15; /* Most effective integer 0 <= x <= 32767 */ +typedef int myf; /* Type of MyFlags in my_funcs */ + /* Macros for converting *constants* to the right type */ +#define INT8(v) (int8) (v) +#define INT16(v) (int16) (v) +#define INT32(v) (int32) (v) +#define MYF(v) STATIC_CAST(myf)(v) + +/* + Defines to make it possible to prioritize register assignments. No + longer that important with modern compilers. +*/ +#ifndef USING_X +#define reg1 register +#define reg2 register +#define reg3 register +#define reg4 register +#define reg5 register +#define reg6 register +#define reg7 register +#define reg8 register +#define reg9 register +#define reg10 register +#define reg11 register +#define reg12 register +#define reg13 register +#define reg14 register +#define reg15 register +#define reg16 register +#endif + +/* + Sometimes we want to make sure that the variable is not put into + a register in debugging mode so we can see its value in the core +*/ + +#ifndef DBUG_OFF +#define dbug_volatile volatile +#else +#define dbug_volatile +#endif + +/* Some helper macros */ +#define YESNO(X) ((X) ? "yes" : "no") + +/* Defines for time function */ +#define SCALE_SEC 100 +#define SCALE_USEC 10000 +#define MY_HOW_OFTEN_TO_ALARM 2 /* How often we want info on screen */ +#define MY_HOW_OFTEN_TO_WRITE 10000 /* How often we want info on screen */ + +/* + Define-funktions for reading and storing in machine independent format + (low byte first) +*/ + +/* Optimized store functions for Intel x86 */ +#if defined(__i386__) || defined(_WIN32) +#define sint2korr(A) (*((const int16 *) (A))) +#define sint3korr(A) ((int32) ((((uchar) (A)[2]) & 128) ? \ + (((uint32) 255L << 24) | \ + (((uint32) (uchar) (A)[2]) << 16) |\ + (((uint32) (uchar) (A)[1]) << 8) | \ + ((uint32) (uchar) (A)[0])) : \ + (((uint32) (uchar) (A)[2]) << 16) |\ + (((uint32) (uchar) (A)[1]) << 8) | \ + ((uint32) (uchar) (A)[0]))) +#define sint4korr(A) (*((const long *) (A))) +#define uint2korr(A) (*((const uint16 *) (A))) +#if defined(HAVE_purify) && !defined(_WIN32) +#define uint3korr(A) (uint32) (((uint32) ((uchar) (A)[0])) +\ + (((uint32) ((uchar) (A)[1])) << 8) +\ + (((uint32) ((uchar) (A)[2])) << 16)) +#else +/* + ATTENTION ! + + Please, note, uint3korr reads 4 bytes (not 3) ! + It means, that you have to provide enough allocated space ! +*/ +#define uint3korr(A) (long) (*((const unsigned int *) (A)) & 0xFFFFFF) +#endif /* HAVE_purify && !_WIN32 */ +#define uint4korr(A) (*((const uint32 *) (A))) +#define uint5korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) +\ + (((uint32) ((uchar) (A)[1])) << 8) +\ + (((uint32) ((uchar) (A)[2])) << 16) +\ + (((uint32) ((uchar) (A)[3])) << 24)) +\ + (((ulonglong) ((uchar) (A)[4])) << 32)) +#define uint6korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) + \ + (((uint32) ((uchar) (A)[1])) << 8) + \ + (((uint32) ((uchar) (A)[2])) << 16) + \ + (((uint32) ((uchar) (A)[3])) << 24)) + \ + (((ulonglong) ((uchar) (A)[4])) << 32) + \ + (((ulonglong) ((uchar) (A)[5])) << 40)) +#define uint8korr(A) (*((const ulonglong *) (A))) +#define sint8korr(A) (*((const longlong *) (A))) +#define int2store(T,A) *((uint16*) (T))= (uint16) (A) +#define int3store(T,A) do { *(T)= (uchar) ((A));\ + *(T+1)=(uchar) (((uint) (A) >> 8));\ + *(T+2)=(uchar) (((A) >> 16)); } while (0) +#define int4store(T,A) *((long *) (T))= (long) (A) +#define int5store(T,A) do { *(T)= (uchar)((A));\ + *((T)+1)=(uchar) (((A) >> 8));\ + *((T)+2)=(uchar) (((A) >> 16));\ + *((T)+3)=(uchar) (((A) >> 24)); \ + *((T)+4)=(uchar) (((A) >> 32)); } while(0) +#define int6store(T,A) do { *(T)= (uchar)((A)); \ + *((T)+1)=(uchar) (((A) >> 8)); \ + *((T)+2)=(uchar) (((A) >> 16)); \ + *((T)+3)=(uchar) (((A) >> 24)); \ + *((T)+4)=(uchar) (((A) >> 32)); \ + *((T)+5)=(uchar) (((A) >> 40)); } while(0) +#define int8store(T,A) *((ulonglong *) (T))= (ulonglong) (A) + +typedef union { + double v; + long m[2]; +} doubleget_union; +#define doubleget(V,M) \ +do { doubleget_union _tmp; \ + _tmp.m[0] = *((const long*)(M)); \ + _tmp.m[1] = *(((const long*) (M))+1); \ + (V) = _tmp.v; } while(0) +#define doublestore(T,V) do { *((long *) T) = ((const doubleget_union *)&V)->m[0]; \ + *(((long *) T)+1) = ((const doubleget_union *)&V)->m[1]; \ + } while (0) +#define float4get(V,M) do { *((float *) &(V)) = *((const float*) (M)); } while(0) +#define float8get(V,M) doubleget((V),(M)) +#define float4store(V,M) memcpy((uchar*) V,(const uchar*) (&M),sizeof(float)) +#define floatstore(T,V) memcpy((uchar*)(T), (const uchar*)(&V),sizeof(float)) +#define floatget(V,M) memcpy((uchar*) &V,(const uchar*) (M),sizeof(float)) +#define float8store(V,M) doublestore((V),(M)) +#else + +/* + We're here if it's not a IA-32 architecture (Win32 and UNIX IA-32 defines + were done before) +*/ +#define sint2korr(A) (int16) (((int16) ((uchar) (A)[0])) +\ + ((int16) ((int16) (A)[1]) << 8)) +#define sint3korr(A) ((int32) ((((uchar) (A)[2]) & 128) ? \ + (((uint32) 255L << 24) | \ + (((uint32) (uchar) (A)[2]) << 16) |\ + (((uint32) (uchar) (A)[1]) << 8) | \ + ((uint32) (uchar) (A)[0])) : \ + (((uint32) (uchar) (A)[2]) << 16) |\ + (((uint32) (uchar) (A)[1]) << 8) | \ + ((uint32) (uchar) (A)[0]))) +#define sint4korr(A) (int32) (((int32) ((uchar) (A)[0])) +\ + (((int32) ((uchar) (A)[1]) << 8)) +\ + (((int32) ((uchar) (A)[2]) << 16)) +\ + (((int32) ((int16) (A)[3]) << 24))) +#define sint8korr(A) (longlong) uint8korr(A) +#define uint2korr(A) (uint16) (((uint16) ((uchar) (A)[0])) +\ + ((uint16) ((uchar) (A)[1]) << 8)) +#define uint3korr(A) (uint32) (((uint32) ((uchar) (A)[0])) +\ + (((uint32) ((uchar) (A)[1])) << 8) +\ + (((uint32) ((uchar) (A)[2])) << 16)) +#define uint4korr(A) (uint32) (((uint32) ((uchar) (A)[0])) +\ + (((uint32) ((uchar) (A)[1])) << 8) +\ + (((uint32) ((uchar) (A)[2])) << 16) +\ + (((uint32) ((uchar) (A)[3])) << 24)) +#define uint5korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) +\ + (((uint32) ((uchar) (A)[1])) << 8) +\ + (((uint32) ((uchar) (A)[2])) << 16) +\ + (((uint32) ((uchar) (A)[3])) << 24)) +\ + (((ulonglong) ((uchar) (A)[4])) << 32)) +#define uint6korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) + \ + (((uint32) ((uchar) (A)[1])) << 8) + \ + (((uint32) ((uchar) (A)[2])) << 16) + \ + (((uint32) ((uchar) (A)[3])) << 24)) + \ + (((ulonglong) ((uchar) (A)[4])) << 32) + \ + (((ulonglong) ((uchar) (A)[5])) << 40)) +#define uint8korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) +\ + (((uint32) ((uchar) (A)[1])) << 8) +\ + (((uint32) ((uchar) (A)[2])) << 16) +\ + (((uint32) ((uchar) (A)[3])) << 24)) +\ + (((ulonglong) (((uint32) ((uchar) (A)[4])) +\ + (((uint32) ((uchar) (A)[5])) << 8) +\ + (((uint32) ((uchar) (A)[6])) << 16) +\ + (((uint32) ((uchar) (A)[7])) << 24))) <<\ + 32)) +#define int2store(T,A) do { uint def_temp= (uint) (A) ;\ + *((uchar*) (T))= (uchar)(def_temp); \ + *((uchar*) (T)+1)=(uchar)((def_temp >> 8)); \ + } while(0) +#define int3store(T,A) do { /*lint -save -e734 */\ + *((uchar*)(T))=(uchar) ((A));\ + *((uchar*) (T)+1)=(uchar) (((A) >> 8));\ + *((uchar*)(T)+2)=(uchar) (((A) >> 16)); \ + /*lint -restore */} while(0) +#define int4store(T,A) do { *((char *)(T))=(char) ((A));\ + *(((char *)(T))+1)=(char) (((A) >> 8));\ + *(((char *)(T))+2)=(char) (((A) >> 16));\ + *(((char *)(T))+3)=(char) (((A) >> 24)); } while(0) +#define int5store(T,A) do { *((char *)(T))= (char)((A)); \ + *(((char *)(T))+1)= (char)(((A) >> 8)); \ + *(((char *)(T))+2)= (char)(((A) >> 16)); \ + *(((char *)(T))+3)= (char)(((A) >> 24)); \ + *(((char *)(T))+4)= (char)(((A) >> 32)); \ + } while(0) +#define int6store(T,A) do { *((char *)(T))= (char)((A)); \ + *(((char *)(T))+1)= (char)(((A) >> 8)); \ + *(((char *)(T))+2)= (char)(((A) >> 16)); \ + *(((char *)(T))+3)= (char)(((A) >> 24)); \ + *(((char *)(T))+4)= (char)(((A) >> 32)); \ + *(((char *)(T))+5)= (char)(((A) >> 40)); \ + } while(0) +#define int8store(T,A) do { uint def_temp= (uint) (A), def_temp2= (uint) ((A) >> 32); \ + int4store((T),def_temp); \ + int4store((T+4),def_temp2); } while(0) +#ifdef WORDS_BIGENDIAN +#define float4store(T,A) do { *(T)= ((uchar *) &A)[3];\ + *((T)+1)=(char) ((uchar *) &A)[2];\ + *((T)+2)=(char) ((uchar *) &A)[1];\ + *((T)+3)=(char) ((uchar *) &A)[0]; } while(0) + +#define float4get(V,M) do { float def_temp;\ + ((uchar*) &def_temp)[0]=(M)[3];\ + ((uchar*) &def_temp)[1]=(M)[2];\ + ((uchar*) &def_temp)[2]=(M)[1];\ + ((uchar*) &def_temp)[3]=(M)[0];\ + (V)=def_temp; } while(0) +#define float8store(T,V) do { *(T)= ((uchar *) &V)[7];\ + *((T)+1)=(char) ((uchar *) &V)[6];\ + *((T)+2)=(char) ((uchar *) &V)[5];\ + *((T)+3)=(char) ((uchar *) &V)[4];\ + *((T)+4)=(char) ((uchar *) &V)[3];\ + *((T)+5)=(char) ((uchar *) &V)[2];\ + *((T)+6)=(char) ((uchar *) &V)[1];\ + *((T)+7)=(char) ((uchar *) &V)[0]; } while(0) + +#define float8get(V,M) do { double def_temp;\ + ((uchar*) &def_temp)[0]=(M)[7];\ + ((uchar*) &def_temp)[1]=(M)[6];\ + ((uchar*) &def_temp)[2]=(M)[5];\ + ((uchar*) &def_temp)[3]=(M)[4];\ + ((uchar*) &def_temp)[4]=(M)[3];\ + ((uchar*) &def_temp)[5]=(M)[2];\ + ((uchar*) &def_temp)[6]=(M)[1];\ + ((uchar*) &def_temp)[7]=(M)[0];\ + (V) = def_temp; } while(0) +#else +#define float4get(V,M) memcpy_fixed((uchar*) &V,(uchar*) (M),sizeof(float)) +#define float4store(V,M) memcpy_fixed((uchar*) V,(uchar*) (&M),sizeof(float)) + +#if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) +#define doublestore(T,V) do { *(((char*)T)+0)=(char) ((uchar *) &V)[4];\ + *(((char*)T)+1)=(char) ((uchar *) &V)[5];\ + *(((char*)T)+2)=(char) ((uchar *) &V)[6];\ + *(((char*)T)+3)=(char) ((uchar *) &V)[7];\ + *(((char*)T)+4)=(char) ((uchar *) &V)[0];\ + *(((char*)T)+5)=(char) ((uchar *) &V)[1];\ + *(((char*)T)+6)=(char) ((uchar *) &V)[2];\ + *(((char*)T)+7)=(char) ((uchar *) &V)[3]; }\ + while(0) +#define doubleget(V,M) do { double def_temp;\ + ((uchar*) &def_temp)[0]=(M)[4];\ + ((uchar*) &def_temp)[1]=(M)[5];\ + ((uchar*) &def_temp)[2]=(M)[6];\ + ((uchar*) &def_temp)[3]=(M)[7];\ + ((uchar*) &def_temp)[4]=(M)[0];\ + ((uchar*) &def_temp)[5]=(M)[1];\ + ((uchar*) &def_temp)[6]=(M)[2];\ + ((uchar*) &def_temp)[7]=(M)[3];\ + (V) = def_temp; } while(0) +#endif /* __FLOAT_WORD_ORDER */ + +#define float8get(V,M) doubleget((V),(M)) +#define float8store(V,M) doublestore((V),(M)) +#endif /* WORDS_BIGENDIAN */ + +#endif /* __i386__ OR _WIN32 */ + +/* + Macro for reading 32-bit integer from network byte order (big-endian) + from unaligned memory location. +*/ +#define int4net(A) (int32) (((uint32) ((uchar) (A)[3])) |\ + (((uint32) ((uchar) (A)[2])) << 8) |\ + (((uint32) ((uchar) (A)[1])) << 16) |\ + (((uint32) ((uchar) (A)[0])) << 24)) +/* + Define-funktions for reading and storing in machine format from/to + short/long to/from some place in memory V should be a (not + register) variable, M is a pointer to byte +*/ + +#ifdef WORDS_BIGENDIAN + +#define ushortget(V,M) do { V = (uint16) (((uint16) ((uchar) (M)[1]))+\ + ((uint16) ((uint16) (M)[0]) << 8)); } while(0) +#define shortget(V,M) do { V = (short) (((short) ((uchar) (M)[1]))+\ + ((short) ((short) (M)[0]) << 8)); } while(0) +#define longget(V,M) do { int32 def_temp;\ + ((uchar*) &def_temp)[0]=(M)[0];\ + ((uchar*) &def_temp)[1]=(M)[1];\ + ((uchar*) &def_temp)[2]=(M)[2];\ + ((uchar*) &def_temp)[3]=(M)[3];\ + (V)=def_temp; } while(0) +#define ulongget(V,M) do { uint32 def_temp;\ + ((uchar*) &def_temp)[0]=(M)[0];\ + ((uchar*) &def_temp)[1]=(M)[1];\ + ((uchar*) &def_temp)[2]=(M)[2];\ + ((uchar*) &def_temp)[3]=(M)[3];\ + (V)=def_temp; } while(0) +#define shortstore(T,A) do { uint def_temp=(uint) (A) ;\ + *(((char*)T)+1)=(char)(def_temp); \ + *(((char*)T)+0)=(char)(def_temp >> 8); } while(0) +#define longstore(T,A) do { *(((char*)T)+3)=((A));\ + *(((char*)T)+2)=(((A) >> 8));\ + *(((char*)T)+1)=(((A) >> 16));\ + *(((char*)T)+0)=(((A) >> 24)); } while(0) + +#define floatget(V,M) memcpy_fixed((uchar*) &V,(uchar*) (M),sizeof(float)) +#define floatstore(T,V) memcpy_fixed((uchar*) (T),(uchar*)(&V),sizeof(float)) +#define doubleget(V,M) memcpy_fixed((uchar*) &V,(uchar*) (M),sizeof(double)) +#define doublestore(T,V) memcpy_fixed((uchar*) (T),(uchar*) &V,sizeof(double)) +#define longlongget(V,M) memcpy_fixed((uchar*) &V,(uchar*) (M),sizeof(ulonglong)) +#define longlongstore(T,V) memcpy_fixed((uchar*) (T),(uchar*) &V,sizeof(ulonglong)) + +#else + +#define ushortget(V,M) do { V = uint2korr(M); } while(0) +#define shortget(V,M) do { V = sint2korr(M); } while(0) +#define longget(V,M) do { V = sint4korr(M); } while(0) +#define ulongget(V,M) do { V = uint4korr(M); } while(0) +#define shortstore(T,V) int2store(T,V) +#define longstore(T,V) int4store(T,V) +#ifndef floatstore +#define floatstore(T,V) memcpy_fixed((uchar*) (T),(uchar*) (&V),sizeof(float)) +#define floatget(V,M) memcpy_fixed((uchar*) &V, (uchar*) (M), sizeof(float)) +#endif +#ifndef doubleget +#define doubleget(V,M) memcpy_fixed((uchar*) &V,(uchar*) (M),sizeof(double)) +#define doublestore(T,V) memcpy_fixed((uchar*) (T),(uchar*) &V,sizeof(double)) +#endif /* doubleget */ +#define longlongget(V,M) memcpy_fixed((uchar*) &V,(uchar*) (M),sizeof(ulonglong)) +#define longlongstore(T,V) memcpy_fixed((uchar*) (T),(uchar*) &V,sizeof(ulonglong)) + +#endif /* WORDS_BIGENDIAN */ + +/* sprintf does not always return the number of bytes :- */ +#ifdef SPRINTF_RETURNS_INT +#define my_sprintf(buff,args) sprintf args +#else +#ifdef SPRINTF_RETURNS_PTR +#define my_sprintf(buff,args) ((int)(sprintf args - buff)) +#else +#define my_sprintf(buff,args) ((ulong) sprintf args, (ulong) strlen(buff)) +#endif +#endif + +#ifndef THREAD +#define thread_safe_increment(V,L) (V)++ +#define thread_safe_decrement(V,L) (V)-- +#define thread_safe_add(V,C,L) (V)+=(C) +#define thread_safe_sub(V,C,L) (V)-=(C) +#define statistic_increment(V,L) (V)++ +#define statistic_decrement(V,L) (V)-- +#define statistic_add(V,C,L) (V)+=(C) +#define statistic_sub(V,C,L) (V)-=(C) +#endif + +#if defined(HAVE_CHARSET_utf8mb3) || defined(HAVE_CHARSET_utf8mb4) +#define MYSQL_UNIVERSAL_CLIENT_CHARSET "utf8" +#else +#define MYSQL_UNIVERSAL_CLIENT_CHARSET MYSQL_DEFAULT_CHARSET_NAME +#endif + +#if defined(EMBEDDED_LIBRARY) && !defined(HAVE_EMBEDDED_PRIVILEGE_CONTROL) +#define NO_EMBEDDED_ACCESS_CHECKS +#endif + +#ifdef HAVE_DLOPEN +#if defined(__WIN__) +#define dlsym(lib, name) GetProcAddress((HMODULE)lib, name) +#define dlopen(libname, unused) LoadLibraryEx(libname, NULL, 0) +#define dlclose(lib) FreeLibrary((HMODULE)lib) +#elif defined(HAVE_DLFCN_H) +#include +#endif +#endif + +/* FreeBSD 2.2.2 does not define RTLD_NOW) */ +#ifndef RTLD_NOW +#define RTLD_NOW 1 +#endif + +#ifndef HAVE_DLERROR +#define dlerror() "" +#endif + + +#ifndef __NETWARE__ +/* + * Include standard definitions of operator new and delete. + */ +#ifdef __cplusplus +#include +#endif +#else +/* + * Define placement versions of operator new and operator delete since + * we don't have when building for Netware. + */ +#ifdef __cplusplus +inline void *operator new(size_t, void *ptr) { return ptr; } +inline void *operator new[](size_t, void *ptr) { return ptr; } +inline void operator delete(void*, void*) { /* Do nothing */ } +inline void operator delete[](void*, void*) { /* Do nothing */ } +#endif +#endif + +/* Length of decimal number represented by INT32. */ +#define MY_INT32_NUM_DECIMAL_DIGITS 11 + +/* Length of decimal number represented by INT64. */ +#define MY_INT64_NUM_DECIMAL_DIGITS 21 + +/* Define some useful general macros (should be done after all headers). */ +#if !defined(max) +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) < (b) ? (a) : (b)) +#endif +/* + Only Linux is known to need an explicit sync of the directory to make sure a + file creation/deletion/renaming in(from,to) this directory durable. +*/ +#ifdef TARGET_OS_LINUX +#define NEED_EXPLICIT_SYNC_DIR 1 +#else +/* + On linux default rwlock scheduling policy is good enough for + waiting_threads.c, on other systems use our special implementation + (which is slower). + + QQ perhaps this should be tested in configure ? how ? +*/ +#define WT_RWLOCKS_USE_MUTEXES 1 +#endif + +#if !defined(__cplusplus) && !defined(bool) +#define bool In_C_you_should_use_my_bool_instead() +#endif + +/* Provide __func__ macro definition for platforms that miss it. */ +#if __STDC_VERSION__ < 199901L +# if __GNUC__ >= 2 +# define __func__ __FUNCTION__ +# else +# define __func__ "" +# endif +#elif defined(_MSC_VER) +# if _MSC_VER < 1300 +# define __func__ "" +# else +# define __func__ __FUNCTION__ +# endif +#elif defined(__BORLANDC__) +# define __func__ __FUNC__ +#else +# define __func__ "" +#endif + +#ifndef HAVE_RINT +/** + All integers up to this number can be represented exactly as double precision + values (DBL_MANT_DIG == 53 for IEEE 754 hardware). +*/ +#define MAX_EXACT_INTEGER ((1LL << DBL_MANT_DIG) - 1) + +/** + rint(3) implementation for platforms that do not have it. + Always rounds to the nearest integer with ties being rounded to the nearest + even integer to mimic glibc's rint() behavior in the "round-to-nearest" + FPU mode. Hardware-specific optimizations are possible (frndint on x86). + Unlike this implementation, hardware will also honor the FPU rounding mode. +*/ + +static inline double rint(double x) +{ + double f, i; + f = modf(x, &i); + + /* + All doubles with absolute values > MAX_EXACT_INTEGER are even anyway, + no need to check it. + */ + if (x > 0.0) + i += (double) ((f > 0.5) || (f == 0.5 && + i <= (double) MAX_EXACT_INTEGER && + (longlong) i % 2)); + else + i -= (double) ((f < -0.5) || (f == -0.5 && + i >= (double) -MAX_EXACT_INTEGER && + (longlong) i % 2)); + return i; +} +#endif /* HAVE_RINT */ + +/* + MYSQL_PLUGIN_IMPORT macro is used to export mysqld data + (i.e variables) for usage in storage engine loadable plugins. + Outside of Windows, it is dummy. +*/ +#ifndef MYSQL_PLUGIN_IMPORT +#if (defined(_WIN32) && defined(MYSQL_DYNAMIC_PLUGIN)) +#define MYSQL_PLUGIN_IMPORT __declspec(dllimport) +#else +#define MYSQL_PLUGIN_IMPORT +#endif +#endif + +#endif /* my_global_h */ diff --git a/mysql_incl/my_libwrap.h b/mysql_incl/my_libwrap.h new file mode 100644 index 0000000..9a85794 --- /dev/null +++ b/mysql_incl/my_libwrap.h @@ -0,0 +1,27 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifdef HAVE_LIBWRAP +#include +#include +#ifdef NEED_SYS_SYSLOG_H +#include +#endif /* NEED_SYS_SYSLOG_H */ + +extern void my_fromhost(struct request_info *req); +extern int my_hosts_access(struct request_info *req); +extern char *my_eval_client(struct request_info *req); + +#endif /* HAVE_LIBWRAP */ diff --git a/mysql_incl/my_list.h b/mysql_incl/my_list.h new file mode 100644 index 0000000..775b565 --- /dev/null +++ b/mysql_incl/my_list.h @@ -0,0 +1,45 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _list_h_ +#define _list_h_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct st_list { + struct st_list *prev,*next; + void *data; +} LIST; + +typedef int (*list_walk_action)(void *,void *); + +extern LIST *list_add(LIST *root,LIST *element); +extern LIST *list_delete(LIST *root,LIST *element); +extern LIST *list_cons(void *data,LIST *root); +extern LIST *list_reverse(LIST *root); +extern void list_free(LIST *root,unsigned int free_data); +extern unsigned int list_length(LIST *); +extern int list_walk(LIST *,list_walk_action action,unsigned char * argument); + +#define list_rest(a) ((a)->next) +#define list_push(a,b) (a)=list_cons((b),(a)) +#define list_pop(A) {LIST *old=(A); (A)=list_delete(old,old) ; my_free((unsigned char *) old,MYF(MY_FAE)); } + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/my_md5.h b/mysql_incl/my_md5.h new file mode 100644 index 0000000..6458f27 --- /dev/null +++ b/mysql_incl/my_md5.h @@ -0,0 +1,54 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* See md5.c for explanation and copyright information. */ + +/* + * $FreeBSD: src/contrib/cvs/lib/md5.h,v 1.2 1999/12/11 15:10:02 peter Exp $ + */ + +/* Unlike previous versions of this code, uint32 need not be exactly + 32 bits, merely 32 bits or more. Choosing a data type which is 32 + bits instead of 64 is not important; speed is considerably more + important. ANSI guarantees that "unsigned long" will be big enough, + and always using it seems to have few disadvantages. */ +typedef uint32 cvs_uint32; + +typedef struct { + cvs_uint32 buf[4]; + cvs_uint32 bits[2]; + unsigned char in[64]; +} my_MD5Context; + +#ifdef __cplusplus +extern "C" { +#endif +void my_MD5Init (my_MD5Context *context); +void my_MD5Update (my_MD5Context *context, + unsigned char const *buf, unsigned len); +void my_MD5Final (unsigned char digest[16], + my_MD5Context *context); + +#ifdef __cplusplus +} +#endif + +#define MY_MD5_HASH(digest,buf,len) \ +do { \ + my_MD5Context ctx; \ + my_MD5Init (&ctx); \ + my_MD5Update (&ctx, buf, len); \ + my_MD5Final (digest, &ctx); \ +} while (0) diff --git a/mysql_incl/my_net.h b/mysql_incl/my_net.h new file mode 100644 index 0000000..18fb3db --- /dev/null +++ b/mysql_incl/my_net.h @@ -0,0 +1,114 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + thread safe version of some common functions: + my_inet_ntoa + + This file is also used to make handling of sockets and ioctl() + portable accross systems. + +*/ + +#ifndef _my_net_h +#define _my_net_h +C_MODE_START + +#include +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_POLL +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#if !defined(__WIN__) && !defined(HAVE_BROKEN_NETINET_INCLUDES) && !defined(__NETWARE__) +#include +#include +#include +#if !defined(alpha_linux_port) +#include +#endif +#endif + +#if defined(__WIN__) +#define O_NONBLOCK 1 /* For emulation of fcntl() */ + +/* + SHUT_RDWR is called SD_BOTH in windows and + is defined to 2 in winsock2.h + #define SD_BOTH 0x02 +*/ +#define SHUT_RDWR 0x02 + +#endif + +/* + On OSes which don't have the in_addr_t, we guess that using uint32 is the best + possible choice. We guess this from the fact that on HP-UX64bit & FreeBSD64bit + & Solaris64bit, in_addr_t is equivalent to uint32. And on Linux32bit too. +*/ +#ifndef HAVE_IN_ADDR_T +#define in_addr_t uint32 +#endif + +/* Thread safe or portable version of some functions */ + +void my_inet_ntoa(struct in_addr in, char *buf); + +/* + Handling of gethostbyname_r() +*/ + +#if !defined(HAVE_GETHOSTBYNAME_R) +struct hostent *my_gethostbyname_r(const char *name, + struct hostent *result, char *buffer, + int buflen, int *h_errnop); +void my_gethostbyname_r_free(); +#elif defined(HAVE_PTHREAD_ATTR_CREATE) || defined(_AIX) || defined(HAVE_GETHOSTBYNAME_R_GLIBC2_STYLE) +struct hostent *my_gethostbyname_r(const char *name, + struct hostent *result, char *buffer, + int buflen, int *h_errnop); +#define my_gethostbyname_r_free() +#if !defined(HAVE_GETHOSTBYNAME_R_GLIBC2_STYLE) && !defined(HPUX10) +#define GETHOSTBYNAME_BUFF_SIZE sizeof(struct hostent_data) +#endif /* !defined(HAVE_GETHOSTBYNAME_R_GLIBC2_STYLE) */ + +#elif defined(HAVE_GETHOSTBYNAME_R_RETURN_INT) +#define GETHOSTBYNAME_BUFF_SIZE sizeof(struct hostent_data) +struct hostent *my_gethostbyname_r(const char *name, + struct hostent *result, char *buffer, + int buflen, int *h_errnop); +#define my_gethostbyname_r_free() +#else +#define my_gethostbyname_r(A,B,C,D,E) gethostbyname_r((A),(B),(C),(D),(E)) +#define my_gethostbyname_r_free() +#endif /* !defined(HAVE_GETHOSTBYNAME_R) */ + +#ifndef GETHOSTBYNAME_BUFF_SIZE +#define GETHOSTBYNAME_BUFF_SIZE 2048 +#endif + +C_MODE_END +#endif diff --git a/mysql_incl/my_no_pthread.h b/mysql_incl/my_no_pthread.h new file mode 100644 index 0000000..b11dbff --- /dev/null +++ b/mysql_incl/my_no_pthread.h @@ -0,0 +1,50 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +#if !defined(_my_no_pthread_h) && !defined(THREAD) +#define _my_no_pthread_h + + +/* + This block is to access some thread-related type definitions + even in builds which do not need thread functions, + as some variables (based on these types) are declared + even in non-threaded builds. + Case in point: 'mf_keycache.c' +*/ +#if defined(__WIN__) +#else /* Normal threads */ +#include + +#endif /* defined(__WIN__) */ + + +/* + This undefs some pthread mutex locks when one isn't using threads + to make thread safe code, that should also work in single thread + environment, easier to use. +*/ +#define pthread_mutex_init(A,B) +#define pthread_mutex_lock(A) +#define pthread_mutex_unlock(A) +#define pthread_mutex_destroy(A) +#define my_rwlock_init(A,B) +#define rw_rdlock(A) +#define rw_wrlock(A) +#define rw_unlock(A) +#define rwlock_destroy(A) + +#endif diff --git a/mysql_incl/my_nosys.h b/mysql_incl/my_nosys.h new file mode 100644 index 0000000..df5639b --- /dev/null +++ b/mysql_incl/my_nosys.h @@ -0,0 +1,52 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Header to remove use of my_functions in functions where we need speed and + where calls to posix functions should work +*/ +#ifndef _my_nosys_h +#define _my_nosys_h +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef __MY_NOSYS__ +#define __MY_NOSYS__ + +#ifndef HAVE_STDLIB_H +#include +#endif + +#undef my_read /* Can be predefined in raid.h */ +#undef my_write +#undef my_seek +#define my_read(a,b,c,d) my_quick_read(a,b,c,d) +#define my_write(a,b,c,d) my_quick_write(a,b,c) +extern size_t my_quick_read(File Filedes,uchar *Buffer,size_t Count, + myf myFlags); +extern size_t my_quick_write(File Filedes,const uchar *Buffer,size_t Count); + +#if !defined(SAFEMALLOC) && defined(USE_HALLOC) +#define my_malloc(a,b) halloc(a,1) +#define my_no_flags_free(a) hfree(a) +#endif + +#endif /* __MY_NOSYS__ */ + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/my_pthread.h b/mysql_incl/my_pthread.h new file mode 100644 index 0000000..ab26860 --- /dev/null +++ b/mysql_incl/my_pthread.h @@ -0,0 +1,734 @@ +/* Copyright (C) 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* Defines to make different thread packages compatible */ + +#ifndef _my_pthread_h +#define _my_pthread_h + +#ifndef ETIME +#define ETIME ETIMEDOUT /* For FreeBSD */ +#endif + +#ifdef __cplusplus +#define EXTERNC extern "C" +extern "C" { +#else +#define EXTERNC +#endif /* __cplusplus */ + +#if defined(__WIN__) +typedef CRITICAL_SECTION pthread_mutex_t; +typedef DWORD pthread_t; +typedef struct thread_attr { + DWORD dwStackSize ; + DWORD dwCreatingFlag ; +} pthread_attr_t ; + +typedef struct { int dummy; } pthread_condattr_t; + +/* Implementation of posix conditions */ + +typedef struct st_pthread_link { + DWORD thread_id; + struct st_pthread_link *next; +} pthread_link; + +typedef struct { + uint32 waiting; + CRITICAL_SECTION lock_waiting; + + enum { + SIGNAL= 0, + BROADCAST= 1, + MAX_EVENTS= 2 + } EVENTS; + + HANDLE events[MAX_EVENTS]; + HANDLE broadcast_block_event; + +} pthread_cond_t; + + +typedef int pthread_mutexattr_t; +#define pthread_self() GetCurrentThreadId() +#define pthread_handler_t EXTERNC void * __cdecl +typedef void * (__cdecl *pthread_handler)(void *); + +/* + Struct and macros to be used in combination with the + windows implementation of pthread_cond_timedwait +*/ + +/* + Declare a union to make sure FILETIME is properly aligned + so it can be used directly as a 64 bit value. The value + stored is in 100ns units. + */ +union ft64 { + FILETIME ft; + __int64 i64; +}; + +struct timespec { + union ft64 tv; + /* The max timeout value in millisecond for pthread_cond_timedwait */ + long max_timeout_msec; +}; + +#define set_timespec_time_nsec(ABSTIME,TIME,NSEC) do { \ + (ABSTIME).tv.i64= (TIME)+(__int64)(NSEC)/100; \ + (ABSTIME).max_timeout_msec= (long)((NSEC)/1000000); \ +} while(0) + +#define set_timespec_nsec(ABSTIME,NSEC) do { \ + union ft64 tv; \ + GetSystemTimeAsFileTime(&tv.ft); \ + set_timespec_time_nsec((ABSTIME), tv.i64, (NSEC)); \ +} while(0) + +int win_pthread_mutex_trylock(pthread_mutex_t *mutex); +int pthread_create(pthread_t *,pthread_attr_t *,pthread_handler,void *); +int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr); +int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); +int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, + struct timespec *abstime); +int pthread_cond_signal(pthread_cond_t *cond); +int pthread_cond_broadcast(pthread_cond_t *cond); +int pthread_cond_destroy(pthread_cond_t *cond); +int pthread_attr_init(pthread_attr_t *connect_att); +int pthread_attr_setstacksize(pthread_attr_t *connect_att,DWORD stack); +int pthread_attr_destroy(pthread_attr_t *connect_att); +struct tm *localtime_r(const time_t *timep,struct tm *tmp); +struct tm *gmtime_r(const time_t *timep,struct tm *tmp); + +void pthread_exit(void *a); +int pthread_join(pthread_t thread, void **value_ptr); + + +#define ETIMEDOUT 145 /* Win32 doesn't have this */ +#define HAVE_LOCALTIME_R 1 +#define _REENTRANT 1 +#define HAVE_PTHREAD_ATTR_SETSTACKSIZE 1 + + +#undef SAFE_MUTEX /* This will cause conflicts */ +#define pthread_key(T,V) DWORD V +#define pthread_key_create(A,B) ((*A=TlsAlloc())==0xFFFFFFFF) +#define pthread_key_delete(A) TlsFree(A) +#define my_pthread_setspecific_ptr(T,V) (!TlsSetValue((T),(V))) +#define pthread_setspecific(A,B) (!TlsSetValue((A),(B))) +#define pthread_getspecific(A) (TlsGetValue(A)) +#define my_pthread_getspecific(T,A) ((T) TlsGetValue(A)) +#define my_pthread_getspecific_ptr(T,V) ((T) TlsGetValue(V)) + +#define pthread_equal(A,B) ((A) == (B)) +#define pthread_mutex_init(A,B) (InitializeCriticalSection(A),0) +#define pthread_mutex_lock(A) (EnterCriticalSection(A),0) +#define pthread_mutex_trylock(A) win_pthread_mutex_trylock((A)) +#define pthread_mutex_unlock(A) (LeaveCriticalSection(A),0) +#define pthread_mutex_destroy(A) DeleteCriticalSection(A) +#define pthread_kill(A,B) pthread_dummy((A) ? 0 : ESRCH) + + +/* Dummy defines for easier code */ +#define pthread_attr_setdetachstate(A,B) pthread_dummy(0) +#define pthread_attr_setscope(A,B) +#define pthread_detach_this_thread() +#define pthread_condattr_init(A) +#define pthread_condattr_destroy(A) +#define pthread_yield() SwitchToThread() + + +#else /* Normal threads */ + +#ifdef HAVE_rts_threads +#define sigwait org_sigwait +#include +#undef sigwait +#endif +#include +#ifndef _REENTRANT +#define _REENTRANT +#endif +#ifdef HAVE_THR_SETCONCURRENCY +#include /* Probably solaris */ +#endif +#ifdef HAVE_SCHED_H +#include +#endif +#ifdef HAVE_SYNCH_H +#include +#endif + +#ifdef __NETWARE__ +void my_pthread_exit(void *status); +#define pthread_exit(A) my_pthread_exit(A) +#endif + +#define pthread_key(T,V) pthread_key_t V +#define my_pthread_getspecific_ptr(T,V) my_pthread_getspecific(T,(V)) +#define my_pthread_setspecific_ptr(T,V) pthread_setspecific(T,(void*) (V)) +#define pthread_detach_this_thread() +#define pthread_handler_t EXTERNC void * +typedef void *(* pthread_handler)(void *); + +/* Test first for RTS or FSU threads */ + +#if defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM) +#define HAVE_rts_threads +extern int my_pthread_create_detached; +#define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C)) +#define PTHREAD_CREATE_DETACHED &my_pthread_create_detached +#define PTHREAD_SCOPE_SYSTEM PTHREAD_SCOPE_GLOBAL +#define PTHREAD_SCOPE_PROCESS PTHREAD_SCOPE_LOCAL +#define USE_ALARM_THREAD +#endif /* defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM) */ + +#if defined(_BSDI_VERSION) && _BSDI_VERSION < 199910 +int sigwait(sigset_t *set, int *sig); +#endif + +#ifndef HAVE_NONPOSIX_SIGWAIT +#define my_sigwait(A,B) sigwait((A),(B)) +#else +int my_sigwait(const sigset_t *set,int *sig); +#endif + +#ifdef HAVE_NONPOSIX_PTHREAD_MUTEX_INIT +#ifndef SAFE_MUTEX +#define pthread_mutex_init(a,b) my_pthread_mutex_noposix_init((a),(b)) +extern int my_pthread_mutex_noposix_init(pthread_mutex_t *mp, + const pthread_mutexattr_t *attr); +#endif /* SAFE_MUTEX */ +#define pthread_cond_init(a,b) my_pthread_cond_noposix_init((a),(b)) +extern int my_pthread_cond_noposix_init(pthread_cond_t *mp, + const pthread_condattr_t *attr); +#endif /* HAVE_NONPOSIX_PTHREAD_MUTEX_INIT */ + +#if defined(HAVE_SIGTHREADMASK) && !defined(HAVE_PTHREAD_SIGMASK) +#define pthread_sigmask(A,B,C) sigthreadmask((A),(B),(C)) +#endif + +#if !defined(HAVE_SIGWAIT) && !defined(HAVE_rts_threads) && !defined(sigwait) && !defined(alpha_linux_port) && !defined(HAVE_NONPOSIX_SIGWAIT) && !defined(HAVE_DEC_3_2_THREADS) && !defined(_AIX) +int sigwait(sigset_t *setp, int *sigp); /* Use our implemention */ +#endif + + +/* + We define my_sigset() and use that instead of the system sigset() so that + we can favor an implementation based on sigaction(). On some systems, such + as Mac OS X, sigset() results in flags such as SA_RESTART being set, and + we want to make sure that no such flags are set. +*/ +#if defined(HAVE_SIGACTION) && !defined(my_sigset) +#define my_sigset(A,B) do { struct sigaction l_s; sigset_t l_set; int l_rc; \ + DBUG_ASSERT((A) != 0); \ + sigemptyset(&l_set); \ + l_s.sa_handler = (B); \ + l_s.sa_mask = l_set; \ + l_s.sa_flags = 0; \ + l_rc= sigaction((A), &l_s, (struct sigaction *) NULL);\ + DBUG_ASSERT(l_rc == 0); \ + } while (0) +#elif defined(HAVE_SIGSET) && !defined(my_sigset) +#define my_sigset(A,B) sigset((A),(B)) +#elif !defined(my_sigset) +#define my_sigset(A,B) signal((A),(B)) +#endif + +#if !defined(HAVE_PTHREAD_ATTR_SETSCOPE) || defined(HAVE_DEC_3_2_THREADS) +#define pthread_attr_setscope(A,B) +#undef HAVE_GETHOSTBYADDR_R /* No definition */ +#endif + +#if defined(HAVE_BROKEN_PTHREAD_COND_TIMEDWAIT) && !defined(SAFE_MUTEX) +extern int my_pthread_cond_timedwait(pthread_cond_t *cond, + pthread_mutex_t *mutex, + struct timespec *abstime); +#define pthread_cond_timedwait(A,B,C) my_pthread_cond_timedwait((A),(B),(C)) +#endif + +#if !defined( HAVE_NONPOSIX_PTHREAD_GETSPECIFIC) +#define my_pthread_getspecific(A,B) ((A) pthread_getspecific(B)) +#else +#define my_pthread_getspecific(A,B) ((A) my_pthread_getspecific_imp(B)) +void *my_pthread_getspecific_imp(pthread_key_t key); +#endif + +#ifndef HAVE_LOCALTIME_R +struct tm *localtime_r(const time_t *clock, struct tm *res); +#endif + +#ifndef HAVE_GMTIME_R +struct tm *gmtime_r(const time_t *clock, struct tm *res); +#endif + +#ifdef HAVE_PTHREAD_CONDATTR_CREATE +/* DCE threads on HPUX 10.20 */ +#define pthread_condattr_init pthread_condattr_create +#define pthread_condattr_destroy pthread_condattr_delete +#endif + +/* FSU THREADS */ +#if !defined(HAVE_PTHREAD_KEY_DELETE) && !defined(pthread_key_delete) +#define pthread_key_delete(A) pthread_dummy(0) +#endif + +#if ((defined(HAVE_PTHREAD_ATTR_CREATE) && !defined(HAVE_SIGWAIT)) || defined(HAVE_DEC_3_2_THREADS)) +/* This is set on AIX_3_2 and Siemens unix (and DEC OSF/1 3.2 too) */ +#define pthread_key_create(A,B) \ + pthread_keycreate(A,(B) ?\ + (pthread_destructor_t) (B) :\ + (pthread_destructor_t) pthread_dummy) +#define pthread_attr_init(A) pthread_attr_create(A) +#define pthread_attr_destroy(A) pthread_attr_delete(A) +#define pthread_attr_setdetachstate(A,B) pthread_dummy(0) +#define pthread_create(A,B,C,D) pthread_create((A),*(B),(C),(D)) +#ifndef pthread_sigmask +#define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C)) +#endif +#define pthread_kill(A,B) pthread_dummy((A) ? 0 : ESRCH) +#undef pthread_detach_this_thread +#define pthread_detach_this_thread() { pthread_t tmp=pthread_self() ; pthread_detach(&tmp); } +#elif !defined(__NETWARE__) /* HAVE_PTHREAD_ATTR_CREATE && !HAVE_SIGWAIT */ +#ifndef HAVE_PTHREAD_KILL +# define HAVE_PTHREAD_KILL +#endif +#endif + +#endif /* defined(__WIN__) */ + +#if defined(HPUX10) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS) +#undef pthread_cond_timedwait +#define pthread_cond_timedwait(a,b,c) my_pthread_cond_timedwait((a),(b),(c)) +int my_pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, + struct timespec *abstime); +#endif + +#if defined(HPUX10) +#define pthread_attr_getstacksize(A,B) my_pthread_attr_getstacksize(A,B) +void my_pthread_attr_getstacksize(pthread_attr_t *attrib, size_t *size); +#endif + +#if defined(HAVE_POSIX1003_4a_MUTEX) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS) +#undef pthread_mutex_trylock +#define pthread_mutex_trylock(a) my_pthread_mutex_trylock((a)) +int my_pthread_mutex_trylock(pthread_mutex_t *mutex); +#endif + +#if !defined(HAVE_PTHREAD_YIELD_ONE_ARG) && !defined(HAVE_PTHREAD_YIELD_ZERO_ARG) +/* no pthread_yield() available */ +#ifdef HAVE_SCHED_YIELD +#define pthread_yield() sched_yield() +#elif defined(HAVE_PTHREAD_YIELD_NP) /* can be Mac OS X */ +#define pthread_yield() pthread_yield_np() +#elif defined(HAVE_THR_YIELD) +#define pthread_yield() thr_yield() +#endif +#endif + +/* + The defines set_timespec and set_timespec_nsec should be used + for calculating an absolute time at which + pthread_cond_timedwait should timeout +*/ + +#define set_timespec(ABSTIME,SEC) set_timespec_nsec((ABSTIME),(SEC)*1000000000ULL) + +#ifndef set_timespec_nsec +#define set_timespec_nsec(ABSTIME,NSEC) \ + set_timespec_time_nsec((ABSTIME),my_getsystime(),(NSEC)) +#endif /* !set_timespec_nsec */ + +/* adapt for two different flavors of struct timespec */ +#ifdef HAVE_TIMESPEC_TS_SEC +#define MY_tv_sec ts_sec +#define MY_tv_nsec ts_nsec +#else +#define MY_tv_sec tv_sec +#define MY_tv_nsec tv_nsec +#endif /* HAVE_TIMESPEC_TS_SEC */ + +#ifndef set_timespec_time_nsec +#define set_timespec_time_nsec(ABSTIME,TIME,NSEC) do { \ + ulonglong nsec= (NSEC); \ + ulonglong now= (TIME) + (nsec/100); \ + (ABSTIME).MY_tv_sec= (now / 10000000ULL); \ + (ABSTIME).MY_tv_nsec= (now % 10000000ULL * 100 + (nsec % 100)); \ +} while(0) +#endif /* !set_timespec_time_nsec */ + +/* safe_mutex adds checking to mutex for easier debugging */ + +#if defined(__NETWARE__) && !defined(SAFE_MUTEX_DETECT_DESTROY) +#define SAFE_MUTEX_DETECT_DESTROY +#endif +struct st_hash; + +typedef struct st_safe_mutex_t +{ + pthread_mutex_t global,mutex; + const char *file, *name; + uint line,count; + myf create_flags, active_flags; + ulong id; + pthread_t thread; + struct st_hash *locked_mutex, *used_mutex; + struct st_safe_mutex_t *prev, *next; +#ifdef SAFE_MUTEX_DETECT_DESTROY + struct st_safe_mutex_info_t *info; /* to track destroying of mutexes */ +#endif +} safe_mutex_t; + +typedef struct st_safe_mutex_deadlock_t +{ + const char *file, *name; + safe_mutex_t *mutex; + uint line; + ulong count; + ulong id; + my_bool warning_only; +} safe_mutex_deadlock_t; + +#ifdef SAFE_MUTEX_DETECT_DESTROY +/* + Used to track the destroying of mutexes. This needs to be a seperate + structure because the safe_mutex_t structure could be freed before + the mutexes are destroyed. +*/ + +typedef struct st_safe_mutex_info_t +{ + struct st_safe_mutex_info_t *next; + struct st_safe_mutex_info_t *prev; + const char *init_file; + uint32 init_line; +} safe_mutex_info_t; +#endif /* SAFE_MUTEX_DETECT_DESTROY */ + +int safe_mutex_init(safe_mutex_t *mp, const pthread_mutexattr_t *attr, + const char *name, myf my_flags, + const char *file, uint line); +int safe_mutex_lock(safe_mutex_t *mp, myf my_flags, const char *file, + uint line); +int safe_mutex_unlock(safe_mutex_t *mp,const char *file, uint line); +int safe_mutex_destroy(safe_mutex_t *mp,const char *file, uint line); +int safe_cond_wait(pthread_cond_t *cond, safe_mutex_t *mp,const char *file, + uint line); +int safe_cond_timedwait(pthread_cond_t *cond, safe_mutex_t *mp, + struct timespec *abstime, const char *file, uint line); +void safe_mutex_global_init(void); +void safe_mutex_end(FILE *file); +void safe_mutex_free_deadlock_data(safe_mutex_t *mp); + + /* Wrappers if safe mutex is actually used */ +#define MYF_TRY_LOCK 1 +#define MYF_NO_DEADLOCK_DETECTION 2 + +#ifdef SAFE_MUTEX +#undef pthread_mutex_init +#undef pthread_mutex_lock +#undef pthread_mutex_unlock +#undef pthread_mutex_destroy +#undef pthread_mutex_wait +#undef pthread_mutex_timedwait +#undef pthread_mutex_t +#undef pthread_cond_wait +#undef pthread_cond_timedwait +#undef pthread_mutex_trylock +#define my_pthread_mutex_init(A,B,C,D) safe_mutex_init((A),(B),(C),(D),__FILE__,__LINE__) +#define pthread_mutex_init(A,B) safe_mutex_init((A),(B),#A,0,__FILE__,__LINE__) +#define pthread_mutex_lock(A) safe_mutex_lock((A), 0, __FILE__, __LINE__) +#define my_pthread_mutex_lock(A,B) safe_mutex_lock((A), (B), __FILE__, __LINE__) +#define pthread_mutex_unlock(A) safe_mutex_unlock((A),__FILE__,__LINE__) +#define pthread_mutex_destroy(A) safe_mutex_destroy((A),__FILE__,__LINE__) +#define pthread_cond_wait(A,B) safe_cond_wait((A),(B),__FILE__,__LINE__) +#define pthread_cond_timedwait(A,B,C) safe_cond_timedwait((A),(B),(C),__FILE__,__LINE__) +#define pthread_mutex_trylock(A) safe_mutex_lock((A), MYF_TRY_LOCK, __FILE__, __LINE__) +#define pthread_mutex_t safe_mutex_t +#define safe_mutex_assert_owner(mp) \ + DBUG_ASSERT((mp)->count > 0 && \ + pthread_equal(pthread_self(), (mp)->thread)) +#define safe_mutex_assert_not_owner(mp) \ + DBUG_ASSERT(! (mp)->count || \ + ! pthread_equal(pthread_self(), (mp)->thread)) +#else +#define my_pthread_mutex_init(A,B,C,D) pthread_mutex_init((A),(B)) +#define my_pthread_mutex_lock(A,B) pthread_mutex_lock(A) +#define safe_mutex_assert_owner(mp) +#define safe_mutex_assert_not_owner(mp) +#endif /* SAFE_MUTEX */ + +#if defined(MY_PTHREAD_FASTMUTEX) && !defined(SAFE_MUTEX) +typedef struct st_my_pthread_fastmutex_t +{ + pthread_mutex_t mutex; + uint spins; + uint rng_state; +} my_pthread_fastmutex_t; +void fastmutex_global_init(void); + +int my_pthread_fastmutex_init(my_pthread_fastmutex_t *mp, + const pthread_mutexattr_t *attr); +int my_pthread_fastmutex_lock(my_pthread_fastmutex_t *mp); + +#undef pthread_mutex_init +#undef pthread_mutex_lock +#undef pthread_mutex_unlock +#undef pthread_mutex_destroy +#undef pthread_mutex_wait +#undef pthread_mutex_timedwait +#undef pthread_mutex_t +#undef pthread_cond_wait +#undef pthread_cond_timedwait +#undef pthread_mutex_trylock +#define pthread_mutex_init(A,B) my_pthread_fastmutex_init((A),(B)) +#define pthread_mutex_lock(A) my_pthread_fastmutex_lock(A) +#define pthread_mutex_unlock(A) pthread_mutex_unlock(&(A)->mutex) +#define pthread_mutex_destroy(A) pthread_mutex_destroy(&(A)->mutex) +#define pthread_cond_wait(A,B) pthread_cond_wait((A),&(B)->mutex) +#define pthread_cond_timedwait(A,B,C) pthread_cond_timedwait((A),&(B)->mutex,(C)) +#define pthread_mutex_trylock(A) pthread_mutex_trylock(&(A)->mutex) +#define pthread_mutex_t my_pthread_fastmutex_t +#endif /* defined(MY_PTHREAD_FASTMUTEX) && !defined(SAFE_MUTEX) */ + + /* READ-WRITE thread locking */ + +#ifdef HAVE_BROKEN_RWLOCK /* For OpenUnix */ +#undef HAVE_PTHREAD_RWLOCK_RDLOCK +#undef HAVE_RWLOCK_INIT +#undef HAVE_RWLOCK_T +#endif + +#if defined(USE_MUTEX_INSTEAD_OF_RW_LOCKS) +/* use these defs for simple mutex locking */ +#define rw_lock_t pthread_mutex_t +#define my_rwlock_init(A,B) pthread_mutex_init((A),(B)) +#define rw_rdlock(A) pthread_mutex_lock((A)) +#define rw_wrlock(A) pthread_mutex_lock((A)) +#define rw_tryrdlock(A) pthread_mutex_trylock((A)) +#define rw_trywrlock(A) pthread_mutex_trylock((A)) +#define rw_unlock(A) pthread_mutex_unlock((A)) +#define rwlock_destroy(A) pthread_mutex_destroy((A)) +#elif defined(HAVE_PTHREAD_RWLOCK_RDLOCK) +#define rw_lock_t pthread_rwlock_t +#define my_rwlock_init(A,B) pthread_rwlock_init((A),(B)) +#define rw_rdlock(A) pthread_rwlock_rdlock(A) +#define rw_wrlock(A) pthread_rwlock_wrlock(A) +#define rw_tryrdlock(A) pthread_rwlock_tryrdlock((A)) +#define rw_trywrlock(A) pthread_rwlock_trywrlock((A)) +#define rw_unlock(A) pthread_rwlock_unlock(A) +#define rwlock_destroy(A) pthread_rwlock_destroy(A) +#elif defined(HAVE_RWLOCK_INIT) +#ifdef HAVE_RWLOCK_T /* For example Solaris 2.6-> */ +#define rw_lock_t rwlock_t +#endif +#define my_rwlock_init(A,B) rwlock_init((A),USYNC_THREAD,0) +#else +/* Use our own version of read/write locks */ +typedef struct _my_rw_lock_t { + pthread_mutex_t lock; /* lock for structure */ + pthread_cond_t readers; /* waiting readers */ + pthread_cond_t writers; /* waiting writers */ + int state; /* -1:writer,0:free,>0:readers */ + int waiters; /* number of waiting writers */ +} my_rw_lock_t; + +#define rw_lock_t my_rw_lock_t +#define rw_rdlock(A) my_rw_rdlock((A)) +#define rw_wrlock(A) my_rw_wrlock((A)) +#define rw_tryrdlock(A) my_rw_tryrdlock((A)) +#define rw_trywrlock(A) my_rw_trywrlock((A)) +#define rw_unlock(A) my_rw_unlock((A)) +#define rwlock_destroy(A) my_rwlock_destroy((A)) + +extern int my_rwlock_init(my_rw_lock_t *, void *); +extern int my_rwlock_destroy(my_rw_lock_t *); +extern int my_rw_rdlock(my_rw_lock_t *); +extern int my_rw_wrlock(my_rw_lock_t *); +extern int my_rw_unlock(my_rw_lock_t *); +extern int my_rw_tryrdlock(my_rw_lock_t *); +extern int my_rw_trywrlock(my_rw_lock_t *); +#endif /* USE_MUTEX_INSTEAD_OF_RW_LOCKS */ + +#define GETHOSTBYADDR_BUFF_SIZE 2048 + +#ifndef HAVE_THR_SETCONCURRENCY +#define thr_setconcurrency(A) pthread_dummy(0) +#endif +#if !defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && ! defined(pthread_attr_setstacksize) +#define pthread_attr_setstacksize(A,B) pthread_dummy(0) +#endif + +/* Define mutex types, see my_thr_init.c */ +#define MY_MUTEX_INIT_SLOW NULL +#ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP +extern pthread_mutexattr_t my_fast_mutexattr; +#define MY_MUTEX_INIT_FAST &my_fast_mutexattr +#else +#define MY_MUTEX_INIT_FAST NULL +#endif +#ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP +extern pthread_mutexattr_t my_errorcheck_mutexattr; +#define MY_MUTEX_INIT_ERRCHK &my_errorcheck_mutexattr +#else +#define MY_MUTEX_INIT_ERRCHK NULL +#endif + +#ifndef ESRCH +/* Define it to something */ +#define ESRCH 1 +#endif + +typedef ulong my_thread_id; + +extern void my_threadattr_global_init(void); +extern my_bool my_thread_global_init(void); +extern void my_thread_global_end(void); +extern my_bool my_thread_init(void); +extern void my_thread_end(void); +extern const char *my_thread_name(void); +extern my_thread_id my_thread_dbug_id(void); +extern int pthread_dummy(int); + +/* All thread specific variables are in the following struct */ + +#define THREAD_NAME_SIZE 10 +#ifndef DEFAULT_THREAD_STACK +#if SIZEOF_CHARP > 4 +/* + MySQL can survive with 32K, but some glibc libraries require > 128K stack + To resolve hostnames. Also recursive stored procedures needs stack. +*/ +#define DEFAULT_THREAD_STACK (256*1024L) +#else +#define DEFAULT_THREAD_STACK (195*1024) +#endif +#endif + +#define MY_PTHREAD_LOCK_READ 0 +#define MY_PTHREAD_LOCK_WRITE 1 + +struct st_my_thread_var +{ + int thr_errno; + pthread_cond_t suspend; + pthread_mutex_t mutex; + pthread_mutex_t * volatile current_mutex; + pthread_cond_t * volatile current_cond; + pthread_t pthread_self; + my_thread_id id; + int cmp_length; + int volatile abort; + my_bool init; + struct st_my_thread_var *next,**prev; + void *opt_info; + uint lock_type; /* used by conditional release the queue */ + void *stack_ends_here; + safe_mutex_t *mutex_in_use; +#ifndef DBUG_OFF + void *dbug; + char name[THREAD_NAME_SIZE+1]; +#endif +}; + +extern struct st_my_thread_var *_my_thread_var(void) __attribute__ ((const)); +extern void **my_thread_var_dbug(); +extern safe_mutex_t **my_thread_var_mutex_in_use(); +extern uint my_thread_end_wait_time; +extern my_bool safe_mutex_deadlock_detector; +#define my_thread_var (_my_thread_var()) +#define my_errno my_thread_var->thr_errno +/* + Keep track of shutdown,signal, and main threads so that my_end() will not + report errors with them +*/ + +/* Which kind of thread library is in use */ + +#define THD_LIB_OTHER 1 +#define THD_LIB_NPTL 2 +#define THD_LIB_LT 4 + +extern uint thd_lib_detected; + +/* + thread_safe_xxx functions are for critical statistic or counters. + The implementation is guaranteed to be thread safe, on all platforms. + Note that the calling code should *not* assume the counter is protected + by the mutex given, as the implementation of these helpers may change + to use my_atomic operations instead. +*/ + +/* + Warning: + When compiling without threads, this file is not included. + See the *other* declarations of thread_safe_xxx in include/my_global.h + + Second warning: + See include/config-win.h, for yet another implementation. +*/ +#ifdef THREAD +#ifndef thread_safe_increment +#define thread_safe_increment(V,L) \ + (pthread_mutex_lock((L)), (V)++, pthread_mutex_unlock((L))) +#define thread_safe_decrement(V,L) \ + (pthread_mutex_lock((L)), (V)--, pthread_mutex_unlock((L))) +#endif + +#ifndef thread_safe_add +#define thread_safe_add(V,C,L) \ + (pthread_mutex_lock((L)), (V)+=(C), pthread_mutex_unlock((L))) +#define thread_safe_sub(V,C,L) \ + (pthread_mutex_lock((L)), (V)-=(C), pthread_mutex_unlock((L))) +#endif +#endif + +/* + statistics_xxx functions are for non critical statistic, + maintained in global variables. + When compiling with SAFE_STATISTICS: + - race conditions can not occur. + - some locking occurs, which may cause performance degradation. + + When compiling without SAFE_STATISTICS: + - race conditions can occur, making the result slightly inaccurate. + - the lock given is not honored. +*/ +#ifdef SAFE_STATISTICS +#define statistic_increment(V,L) thread_safe_increment((V),(L)) +#define statistic_decrement(V,L) thread_safe_decrement((V),(L)) +#define statistic_add(V,C,L) thread_safe_add((V),(C),(L)) +#define statistic_sub(V,C,L) thread_safe_sub((V),(C),(L)) +#else +#define statistic_decrement(V,L) (V)-- +#define statistic_increment(V,L) (V)++ +#define statistic_add(V,C,L) (V)+=(C) +#define statistic_sub(V,C,L) (V)-=(C) +#endif /* SAFE_STATISTICS */ + +/* + No locking needed, the counter is owned by the thread +*/ +#define status_var_increment(V) (V)++ +#define status_var_decrement(V) (V)-- +#define status_var_add(V,C) (V)+=(C) +#define status_var_sub(V,C) (V)-=(C) + +#ifdef __cplusplus +} +#endif +#endif /* _my_ptread_h */ diff --git a/mysql_incl/my_stacktrace.h b/mysql_incl/my_stacktrace.h new file mode 100644 index 0000000..e7ce42c --- /dev/null +++ b/mysql_incl/my_stacktrace.h @@ -0,0 +1,66 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _my_stacktrace_h_ +#define _my_stacktrace_h_ + +#include + +#ifdef TARGET_OS_LINUX +#if defined (__x86_64__) || defined (__i386__) || \ + (defined(__alpha__) && defined(__GNUC__)) +#define HAVE_STACKTRACE 1 +#endif +#elif defined(__WIN__) +#define HAVE_STACKTRACE 1 +#endif + +#if HAVE_BACKTRACE && (HAVE_BACKTRACE_SYMBOLS || HAVE_BACKTRACE_SYMBOLS_FD) +#undef HAVE_STACKTRACE +#define HAVE_STACKTRACE 1 +#endif + +#if !defined(__NETWARE__) +#define HAVE_WRITE_CORE +#endif + +#if HAVE_BACKTRACE && HAVE_BACKTRACE_SYMBOLS && \ + HAVE_CXXABI_H && HAVE_ABI_CXA_DEMANGLE && \ + HAVE_WEAK_SYMBOL +#define BACKTRACE_DEMANGLE 1 +#endif + +C_MODE_START + +#if defined(HAVE_STACKTRACE) || defined(HAVE_BACKTRACE) +void my_init_stacktrace(); +void my_print_stacktrace(uchar* stack_bottom, ulong thread_stack); +void my_safe_print_str(const char* name, const char* val, int max_len); +void my_write_core(int sig); +#if BACKTRACE_DEMANGLE +char *my_demangle(const char *mangled_name, int *status); +#endif +#ifdef __WIN__ +void my_set_exception_pointers(EXCEPTION_POINTERS *ep); +#endif +#endif + +#ifdef HAVE_WRITE_CORE +void my_write_core(int sig); +#endif + +C_MODE_END + +#endif /* _my_stacktrace_h_ */ diff --git a/mysql_incl/my_sys.h b/mysql_incl/my_sys.h new file mode 100644 index 0000000..c8ec791 --- /dev/null +++ b/mysql_incl/my_sys.h @@ -0,0 +1,1082 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/** + @file + mysys library API +*/ + +#ifndef _my_sys_h +#define _my_sys_h +C_MODE_START + +#ifdef HAVE_AIOWAIT +#include /* Used by record-cache */ +typedef struct my_aio_result { + aio_result_t result; + int pending; +} my_aio_result; +#endif + +#ifndef THREAD +extern int NEAR my_errno; /* Last error in mysys */ +#else +#include +#endif + +#include /* for CHARSET_INFO */ +#include +#include + +#define MYSYS_PROGRAM_DONT_USE_CURSES() { error_handler_hook = my_message_no_curses; mysys_uses_curses=0;} +#define MY_INIT(name); { my_progname= name; my_init(); } + +/** + Max length of an error message generated by mysys utilities. + Some mysys functions produce error messages. These mostly go + to stderr. + This constant defines the size of the buffer used to format + the message. It should be kept in sync with MYSQL_ERRMSG_SIZE, + since sometimes mysys errors are stored in the server diagnostics + area, and we would like to avoid unexpected truncation. +*/ +#define MYSYS_ERRMSG_SIZE (512) + +#define MY_FILE_ERROR ((size_t) -1) + + /* General bitmaps for my_func's */ +#define MY_FFNF 1 /* Fatal if file not found */ +#define MY_FNABP 2 /* Fatal if not all bytes read/writen */ +#define MY_NABP 4 /* Error if not all bytes read/writen */ +#define MY_FAE 8 /* Fatal if any error */ +#define MY_WME 16 /* Write message on error */ +#define MY_WAIT_IF_FULL 32 /* Wait and try again if disk full error */ +#define MY_IGNORE_BADFD 32 /* my_sync: ignore 'bad descriptor' errors */ +#define MY_SYNC_DIR 1024 /* my_create/delete/rename: sync directory */ +#define MY_RAID 64 /* Support for RAID */ +#define MY_FULL_IO 512 /* For my_read - loop intil I/O is complete */ +#define MY_DONT_CHECK_FILESIZE 128 /* Option to init_io_cache() */ +#define MY_LINK_WARNING 32 /* my_redel() gives warning if links */ +#define MY_COPYTIME 64 /* my_redel() copys time */ +#define MY_DELETE_OLD 256 /* my_create_with_symlink() */ +#define MY_RESOLVE_LINK 128 /* my_realpath(); Only resolve links */ +#define MY_HOLD_ORIGINAL_MODES 128 /* my_copy() holds to file modes */ +#define MY_REDEL_MAKE_BACKUP 256 +#define MY_SEEK_NOT_DONE 32 /* my_lock may have to do a seek */ +#define MY_SHORT_WAIT 64 /* my_lock() don't wait if can't lock */ +#define MY_FORCE_LOCK 128 /* use my_lock() even if disable_locking */ +#define MY_NO_WAIT 256 /* my_lock() don't wait at all */ +#define MY_ZEROFILL 32 /* my_malloc(), fill array with zero */ +#define MY_ALLOW_ZERO_PTR 64 /* my_realloc() ; zero ptr -> malloc */ +#define MY_FREE_ON_ERROR 128 /* my_realloc() ; Free old ptr on error */ +#define MY_HOLD_ON_ERROR 256 /* my_realloc() ; Return old ptr on error */ +#define MY_DONT_OVERWRITE_FILE 2048 /* my_copy: Don't overwrite file */ +#define MY_THREADSAFE 2048 /* my_seek(): lock fd mutex */ + +#define MY_CHECK_ERROR 1 /* Params to my_end; Check open-close */ +#define MY_GIVE_INFO 2 /* Give time info about process*/ +#define MY_DONT_FREE_DBUG 4 /* Do not call DBUG_END() in my_end() */ + +#define MY_REMOVE_NONE 0 /* Params for modify_defaults_file */ +#define MY_REMOVE_OPTION 1 +#define MY_REMOVE_SECTION 2 + +#define ME_HIGHBYTE 8 /* Shift for colours */ +#define ME_NOCUR 1 /* Don't use curses message */ +#define ME_OLDWIN 2 /* Use old window */ +#define ME_BELL 4 /* Ring bell then printing message */ +#define ME_HOLDTANG 8 /* Don't delete last keys */ +#define ME_WAITTOT 16 /* Wait for errtime secs of for a action */ +#define ME_WAITTANG 32 /* Wait for a user action */ +#define ME_NOREFRESH 64 /* Dont refresh screen */ +#define ME_NOINPUT 128 /* Dont use the input libary */ +#define ME_COLOUR1 ((1 << ME_HIGHBYTE)) /* Possibly error-colours */ +#define ME_COLOUR2 ((2 << ME_HIGHBYTE)) +#define ME_COLOUR3 ((3 << ME_HIGHBYTE)) +#define ME_FATALERROR 1024 /* Fatal statement error */ +#define ME_JUST_INFO 8192 /**< not error but just info */ +#define ME_JUST_WARNING 16384 /**< not error but just warning */ + + /* Bits in last argument to fn_format */ +#define MY_REPLACE_DIR 1 /* replace dir in name with 'dir' */ +#define MY_REPLACE_EXT 2 /* replace extension with 'ext' */ +#define MY_UNPACK_FILENAME 4 /* Unpack name (~ -> home) */ +#define MY_PACK_FILENAME 8 /* Pack name (home -> ~) */ +#define MY_RESOLVE_SYMLINKS 16 /* Resolve all symbolic links */ +#define MY_RETURN_REAL_PATH 32 /* return full path for file */ +#define MY_SAFE_PATH 64 /* Return NULL if too long path */ +#define MY_RELATIVE_PATH 128 /* name is relative to 'dir' */ +#define MY_APPEND_EXT 256 /* add 'ext' as additional extension*/ + + + /* My seek flags */ +#define MY_SEEK_SET 0 +#define MY_SEEK_CUR 1 +#define MY_SEEK_END 2 + + /* Some constants */ +#define MY_WAIT_FOR_USER_TO_FIX_PANIC 60 /* in seconds */ +#define MY_WAIT_GIVE_USER_A_MESSAGE 10 /* Every 10 times of prev */ +#define MIN_COMPRESS_LENGTH 50 /* Don't compress small bl. */ +#define DFLT_INIT_HITS 3 + + /* root_alloc flags */ +#define MY_KEEP_PREALLOC 1 +#define MY_MARK_BLOCKS_FREE 2 /* move used to free list and reuse them */ + + /* Internal error numbers (for assembler functions) */ +#define MY_ERRNO_EDOM 33 +#define MY_ERRNO_ERANGE 34 + + /* Bits for get_date timeflag */ +#define GETDATE_DATE_TIME 1 +#define GETDATE_SHORT_DATE 2 +#define GETDATE_HHMMSSTIME 4 +#define GETDATE_GMT 8 +#define GETDATE_FIXEDLENGTH 16 + + /* defines when allocating data */ +#ifdef SAFEMALLOC +#define my_malloc(SZ,FLAG) _mymalloc((SZ), __FILE__, __LINE__, FLAG ) +#define my_malloc_ci(SZ,FLAG) _mymalloc((SZ), sFile, uLine, FLAG ) +#define my_realloc(PTR,SZ,FLAG) _myrealloc((PTR), (SZ), __FILE__, __LINE__, FLAG ) +#define my_checkmalloc() _sanity( __FILE__, __LINE__ ) +#define my_free(PTR,FLAG) _myfree((PTR), __FILE__, __LINE__,FLAG) +#define my_memdup(A,B,C) _my_memdup((A),(B), __FILE__,__LINE__,C) +#define my_strdup(A,C) _my_strdup((A), __FILE__,__LINE__,C) +#define my_strndup(A,B,C) _my_strndup((A),(B),__FILE__,__LINE__,C) +#define QUICK_SAFEMALLOC sf_malloc_quick=1 +#define NORMAL_SAFEMALLOC sf_malloc_quick=0 +extern uint sf_malloc_prehunc,sf_malloc_endhunc,sf_malloc_quick; +extern ulonglong sf_malloc_mem_limit; + +#define CALLER_INFO_PROTO , const char *sFile, uint uLine +#define CALLER_INFO , __FILE__, __LINE__ +#define ORIG_CALLER_INFO , sFile, uLine +#else +#define my_checkmalloc() +#undef TERMINATE +#define TERMINATE(A,B) {} +#define QUICK_SAFEMALLOC +#define NORMAL_SAFEMALLOC +extern void *my_malloc(size_t Size,myf MyFlags); +#define my_malloc_ci(SZ,FLAG) my_malloc( SZ, FLAG ) +extern void *my_realloc(void *oldpoint, size_t Size, myf MyFlags); +extern void my_no_flags_free(void *ptr); +extern void *my_memdup(const void *from,size_t length,myf MyFlags); +extern char *my_strdup(const char *from,myf MyFlags); +extern char *my_strndup(const char *from, size_t length, + myf MyFlags); +/* we do use FG (as a no-op) in below so that a typo on FG is caught */ +#define my_free(PTR,FG) ((void)FG,my_no_flags_free(PTR)) +#define CALLER_INFO_PROTO /* nothing */ +#define CALLER_INFO /* nothing */ +#define ORIG_CALLER_INFO /* nothing */ +#endif + +/* + ERROR INJECTION: Non-thread-safe global variable to request error inject. + Set this variable to non-zero to request the next my_malloc() to fail. + This works with my_malloc.c:my_malloc() and safemalloc.c:_mymalloc(). + If using this in tests, note that the error messages produced by + my_malloc and safemalloc are different. You may need to modify the + results with --replace_regex. You may find examples in + client/backup_stream.c and backup_client_coverage.test. + The global variable is defined in my_static.c. +*/ +IF_DBUG(extern int my_malloc_error_inject); + +#ifdef HAVE_LARGE_PAGES +extern uint my_get_large_page_size(void); +extern uchar * my_large_malloc(size_t size, myf my_flags); +extern void my_large_free(uchar * ptr, myf my_flags); +#else +#define my_get_large_page_size() (0) +#define my_large_malloc(A,B) my_malloc_lock((A),(B)) +#define my_large_free(A,B) my_free_lock((A),(B)) +#endif /* HAVE_LARGE_PAGES */ + +#ifdef HAVE_ALLOCA +#if defined(_AIX) && !defined(__GNUC__) && !defined(_AIX43) +#pragma alloca +#endif /* _AIX */ +#if defined(__MWERKS__) +#undef alloca +#define alloca _alloca +#endif /* __MWERKS__ */ +#if defined(__GNUC__) && !defined(HAVE_ALLOCA_H) && ! defined(alloca) +#define alloca __builtin_alloca +#endif /* GNUC */ +#define my_alloca(SZ) alloca((size_t) (SZ)) +#define my_afree(PTR) {} +#else +#define my_alloca(SZ) my_malloc(SZ,MYF(0)) +#define my_afree(PTR) my_free(PTR,MYF(MY_WME)) +#endif /* HAVE_ALLOCA */ + +#ifndef errno /* did we already get it? */ +#ifdef HAVE_ERRNO_AS_DEFINE +#include /* errno is a define */ +#else +extern int errno; /* declare errno */ +#endif +#endif /* #ifndef errno */ +extern char *home_dir; /* Home directory for user */ +extern const char *my_progname; /* program-name (printed in errors) */ +extern const char *my_progname_short; /* like above but without directory */ +extern char NEAR curr_dir[]; /* Current directory for user */ +extern void (*error_handler_hook)(uint my_err, const char *str,myf MyFlags); +extern void (*fatal_error_handler_hook)(uint my_err, const char *str, + myf MyFlags); +extern uint my_file_limit; +extern ulong my_thread_stack_size; + +extern const char *(*proc_info_hook)(void *, const char *, const char *, + const char *, const unsigned int); + +#if defined(ENABLED_DEBUG_SYNC) +extern void (*debug_sync_C_callback_ptr)(const char *, size_t); +#define DEBUG_SYNC_C(_sync_point_name_) do { \ + if (debug_sync_C_callback_ptr != NULL) \ + (*debug_sync_C_callback_ptr)(STRING_WITH_LEN(_sync_point_name_)); } \ + while(0) +#else +#define DEBUG_SYNC_C(_sync_point_name_) +#endif /* defined(ENABLED_DEBUG_SYNC) */ + +#ifdef HAVE_LARGE_PAGES +extern my_bool my_use_large_pages; +extern uint my_large_page_size; +#endif + +/* charsets */ +#define MY_ALL_CHARSETS_SIZE 2048 +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *default_charset_info; +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *all_charsets[MY_ALL_CHARSETS_SIZE]; +extern CHARSET_INFO compiled_charsets[]; + +/* statistics */ +extern ulong my_file_opened,my_stream_opened, my_tmp_file_created; +extern ulong my_file_total_opened; +extern uint mysys_usage_id; +extern my_bool my_init_done; + + /* Point to current my_message() */ +extern void (*my_sigtstp_cleanup)(void), + /* Executed before jump to shell */ + (*my_sigtstp_restart)(void), + (*my_abort_hook)(int); + /* Executed when comming from shell */ +extern MYSQL_PLUGIN_IMPORT int NEAR my_umask; /* Default creation mask */ +extern int NEAR my_umask_dir, + NEAR my_recived_signals, /* Signals we have got */ + NEAR my_safe_to_handle_signal, /* Set when allowed to SIGTSTP */ + NEAR my_dont_interrupt; /* call remember_intr when set */ +extern my_bool NEAR mysys_uses_curses, my_use_symdir; +extern size_t sf_malloc_cur_memory, sf_malloc_max_memory; + +extern ulong my_default_record_cache_size; +extern my_bool NEAR my_disable_locking,NEAR my_disable_async_io, + NEAR my_disable_flush_key_blocks, NEAR my_disable_symlinks; +extern char wild_many,wild_one,wild_prefix; +extern const char *charsets_dir; +/* from default.c */ +extern char *my_defaults_extra_file; +extern const char *my_defaults_group_suffix; +extern const char *my_defaults_file; + +extern my_bool timed_mutexes; + +typedef struct wild_file_pack /* Struct to hold info when selecting files */ +{ + uint wilds; /* How many wildcards */ + uint not_pos; /* Start of not-theese-files */ + char * *wild; /* Pointer to wildcards */ +} WF_PACK; + +enum loglevel { + ERROR_LEVEL, + WARNING_LEVEL, + INFORMATION_LEVEL +}; + +enum cache_type +{ + TYPE_NOT_SET= 0, READ_CACHE, WRITE_CACHE, + SEQ_READ_APPEND /* sequential read or append */, + READ_FIFO, READ_NET,WRITE_NET}; + +enum flush_type +{ + FLUSH_KEEP, /* flush block and keep it in the cache */ + FLUSH_RELEASE, /* flush block and remove it from the cache */ + FLUSH_IGNORE_CHANGED, /* remove block from the cache */ + /* + As my_disable_flush_pagecache_blocks is always 0, the following option + is strictly equivalent to FLUSH_KEEP + */ + FLUSH_FORCE_WRITE, + /** + @brief like FLUSH_KEEP but return immediately if file is already being + flushed (even partially) by another thread; only for page cache, + forbidden for key cache. + */ + FLUSH_KEEP_LAZY +}; + +typedef struct st_record_cache /* Used when cacheing records */ +{ + File file; + int rc_seek,error,inited; + uint rc_length,read_length,reclength; + my_off_t rc_record_pos,end_of_file; + uchar *rc_buff,*rc_buff2,*rc_pos,*rc_end,*rc_request_pos; +#ifdef HAVE_AIOWAIT + int use_async_io; + my_aio_result aio_result; +#endif + enum cache_type type; +} RECORD_CACHE; + +enum file_type +{ + UNOPEN = 0, FILE_BY_OPEN, FILE_BY_CREATE, STREAM_BY_FOPEN, STREAM_BY_FDOPEN, + FILE_BY_MKSTEMP, FILE_BY_DUP +}; + +struct st_my_file_info +{ + char *name; +#ifdef _WIN32 + HANDLE fhandle; /* win32 file handle */ + int oflag; /* open flags, e.g O_APPEND */ +#endif + enum file_type type; +#if defined(THREAD) && !defined(HAVE_PREAD) && !defined(_WIN32) + pthread_mutex_t mutex; +#endif +}; + +extern struct st_my_file_info *my_file_info; + +typedef struct st_dynamic_array +{ + uchar *buffer; + uint elements,max_element; + uint alloc_increment; + uint size_of_element; +} DYNAMIC_ARRAY; + +typedef struct st_my_tmpdir +{ + DYNAMIC_ARRAY full_list; + char **list; + uint cur, max; +#ifdef THREAD + pthread_mutex_t mutex; +#endif +} MY_TMPDIR; + +typedef struct st_dynamic_string +{ + char *str; + size_t length,max_length,alloc_increment; +} DYNAMIC_STRING; + +struct st_io_cache; +/** Function called when certain events happen to an IO_CACHE */ +typedef int (*IO_CACHE_CALLBACK)(struct st_io_cache *cache, + const uchar *buffert, uint length, + my_off_t filepos); + +#ifdef THREAD +typedef struct st_io_cache_share +{ + pthread_mutex_t mutex; /* To sync on reads into buffer. */ + pthread_cond_t cond; /* To wait for signals. */ + pthread_cond_t cond_writer; /* For a synchronized writer. */ + /* Offset in file corresponding to the first byte of buffer. */ + my_off_t pos_in_file; + /* If a synchronized write cache is the source of the data. */ + struct st_io_cache *source_cache; + uchar *buffer; /* The read buffer. */ + uchar *read_end; /* Behind last valid byte of buffer. */ + int running_threads; /* threads not in lock. */ + int total_threads; /* threads sharing the cache. */ + int error; /* Last error. */ +#ifdef NOT_YET_IMPLEMENTED + /* whether the structure should be free'd */ + my_bool alloced; +#endif +} IO_CACHE_SHARE; +#endif + +typedef struct st_io_cache /* Used when cacheing files */ +{ + /* Offset in file corresponding to the first byte of uchar* buffer. */ + my_off_t pos_in_file; + /* + The offset of end of file for READ_CACHE and WRITE_CACHE. + For SEQ_READ_APPEND it the maximum of the actual end of file and + the position represented by read_end. + */ + my_off_t end_of_file; + /* Points to current read position in the buffer */ + uchar *read_pos; + /* the non-inclusive boundary in the buffer for the currently valid read */ + uchar *read_end; + uchar *buffer; /* The read buffer */ + /* Used in ASYNC_IO */ + uchar *request_pos; + + /* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */ + uchar *write_buffer; + /* + Only used in SEQ_READ_APPEND, and points to the current read position + in the write buffer. Note that reads in SEQ_READ_APPEND caches can + happen from both read buffer (uchar* buffer) and write buffer + (uchar* write_buffer). + */ + uchar *append_read_pos; + /* Points to current write position in the write buffer */ + uchar *write_pos; + /* The non-inclusive boundary of the valid write area */ + uchar *write_end; + + /* + Current_pos and current_end are convenience variables used by + my_b_tell() and other routines that need to know the current offset + current_pos points to &write_pos, and current_end to &write_end in a + WRITE_CACHE, and &read_pos and &read_end respectively otherwise + */ + uchar **current_pos, **current_end; +#ifdef THREAD + /* + The lock is for append buffer used in SEQ_READ_APPEND cache + need mutex copying from append buffer to read buffer. + */ + pthread_mutex_t append_buffer_lock; + /* + The following is used when several threads are reading the + same file in parallel. They are synchronized on disk + accesses reading the cached part of the file asynchronously. + It should be set to NULL to disable the feature. Only + READ_CACHE mode is supported. + */ + IO_CACHE_SHARE *share; +#endif + /* + A caller will use my_b_read() macro to read from the cache + if the data is already in cache, it will be simply copied with + memcpy() and internal variables will be accordinging updated with + no functions invoked. However, if the data is not fully in the cache, + my_b_read() will call read_function to fetch the data. read_function + must never be invoked directly. + */ + int (*read_function)(struct st_io_cache *,uchar *,size_t); + /* + Same idea as in the case of read_function, except my_b_write() needs to + be replaced with my_b_append() for a SEQ_READ_APPEND cache + */ + int (*write_function)(struct st_io_cache *,const uchar *,size_t); + /* + Specifies the type of the cache. Depending on the type of the cache + certain operations might not be available and yield unpredicatable + results. Details to be documented later + */ + enum cache_type type; + /* + Callbacks were added and are currently used for binary logging of LOAD + DATA INFILE - when a block is read from the file, we create a block + create/append event, and when IO_CACHE is closed, we create an end event; + also used to write the MyISAM WRITE_CACHE blocks to the MyISAM physical + log. These functions could, of course be used for other things. Note: some + callbacks share the same argument ("arg"). + */ + IO_CACHE_CALLBACK pre_read; /**< called before reading from disk */ + IO_CACHE_CALLBACK post_read; /**< called after reading from disk */ + IO_CACHE_CALLBACK pre_close; /**< called before ending the cache */ + /** Called _after_ writing to disk; not honoured by SEQ_READ_APPEND */ + IO_CACHE_CALLBACK post_write; + /* + Counts the number of times, when we were forced to use disk. We use it to + increase the binlog_cache_disk_use status variable. + */ + ulong disk_writes; + void *arg; /**< used by pre/post_read,post_write */ + char *file_name; /* if used with 'open_cached_file' */ + char *dir,*prefix; + File file; /* file descriptor */ + /* + seek_not_done is set by my_b_seek() to inform the upcoming read/write + operation that a seek needs to be preformed prior to the actual I/O + error is 0 if the cache operation was successful, -1 if there was a + "hard" error, and the actual number of I/O-ed bytes if the read/write was + partial. + */ + int seek_not_done,error; + /** + Cumulative 'error' since last [re]init_io_cache(). Useful if cache's user + polls for errors only once in a while. + */ + int hard_write_error_in_the_past; + /* buffer_length is memory size allocated for buffer or write_buffer */ + size_t buffer_length; + /* read_length is the same as buffer_length except when we use async io */ + size_t read_length; + myf myflags; /* Flags used to my_read/my_write */ + /* + alloced_buffer is 1 if the buffer was allocated by init_io_cache() and + 0 if it was supplied by the user. + Currently READ_NET is the only one that will use a buffer allocated + somewhere else + */ + my_bool alloced_buffer; +#ifdef HAVE_AIOWAIT + /* + As inidicated by ifdef, this is for async I/O, which is not currently + used (because it's not reliable on all systems) + */ + uint inited; + my_off_t aio_read_pos; + my_aio_result aio_result; +#endif +} IO_CACHE; + +typedef int (*qsort2_cmp)(const void *, const void *, const void *); + + /* defines for mf_iocache */ + + /* Test if buffer is inited */ +#define my_b_clear(info) (info)->buffer=0 +#define my_b_inited(info) (info)->buffer +#define my_b_EOF INT_MIN + +#define my_b_read(info,Buffer,Count) \ + ((info)->read_pos + (Count) <= (info)->read_end ?\ + (memcpy(Buffer,(info)->read_pos,(size_t) (Count)), \ + ((info)->read_pos+=(Count)),0) :\ + (*(info)->read_function)((info),Buffer,Count)) + +#define my_b_write(info,Buffer,Count) \ + ((info)->write_pos + (Count) <=(info)->write_end ?\ + (memcpy((info)->write_pos, (Buffer), (size_t)(Count)),\ + ((info)->write_pos+=(Count)),0) : \ + (*(info)->write_function)((info),(Buffer),(Count))) + +#define my_b_get(info) \ + ((info)->read_pos != (info)->read_end ?\ + ((info)->read_pos++, (int) (uchar) (info)->read_pos[-1]) :\ + _my_b_get(info)) + + /* my_b_write_byte dosn't have any err-check */ +#define my_b_write_byte(info,chr) \ + (((info)->write_pos < (info)->write_end) ?\ + ((*(info)->write_pos++)=(chr)) :\ + (_my_b_write(info,0,0) , ((*(info)->write_pos++)=(chr)))) + +#define my_b_fill_cache(info) \ + (((info)->read_end=(info)->read_pos),(*(info)->read_function)(info,0,0)) + +#define my_b_tell(info) ((info)->pos_in_file + \ + (size_t) (*(info)->current_pos - (info)->request_pos)) + +#define my_b_get_buffer_start(info) (info)->request_pos +#define my_b_get_bytes_in_buffer(info) (char*) (info)->read_end - \ + (char*) my_b_get_buffer_start(info) +#define my_b_get_pos_in_file(info) (info)->pos_in_file + +/* tell write offset in the SEQ_APPEND cache */ +int my_b_copy_to_file(IO_CACHE *cache, FILE *file); +my_off_t my_b_append_tell(IO_CACHE* info); +my_off_t my_b_safe_tell(IO_CACHE* info); /* picks the correct tell() */ + +#define my_b_bytes_in_cache(info) (size_t) (*(info)->current_end - \ + *(info)->current_pos) + +typedef uint32 ha_checksum; +extern ha_checksum my_crc_dbug_check; + +/* Define the type of function to be passed to process_default_option_files */ +typedef int (*Process_option_func)(void *ctx, const char *group_name, + const char *option); + +#include + + + /* Prototypes for mysys and my_func functions */ + +extern int my_copy(const char *from,const char *to,myf MyFlags); +extern int my_append(const char *from,const char *to,myf MyFlags); +extern int my_delete(const char *name,myf MyFlags); +extern int my_getwd(char * buf,size_t size,myf MyFlags); +extern int my_setwd(const char *dir,myf MyFlags); +extern int my_lock(File fd,int op,my_off_t start, my_off_t length,myf MyFlags); +extern void *my_once_alloc(size_t Size,myf MyFlags); +extern void my_once_free(void); +extern char *my_once_strdup(const char *src,myf myflags); +extern void *my_once_memdup(const void *src, size_t len, myf myflags); +extern File my_open(const char *FileName,int Flags,myf MyFlags); +extern File my_register_filename(File fd, const char *FileName, + enum file_type type_of_file, + uint error_message_number, myf MyFlags); +extern File my_create(const char *FileName,int CreateFlags, + int AccessFlags, myf MyFlags); +extern int my_close(File Filedes,myf MyFlags); +extern File my_dup(File file, myf MyFlags); +extern int my_mkdir(const char *dir, int Flags, myf MyFlags); +extern int my_readlink(char *to, const char *filename, myf MyFlags); +extern int my_is_symlink(const char *filename); +extern int my_realpath(char *to, const char *filename, myf MyFlags); +extern File my_create_with_symlink(const char *linkname, const char *filename, + int createflags, int access_flags, + myf MyFlags); +extern int my_delete_with_symlink(const char *name, myf MyFlags); +extern int my_rename_with_symlink(const char *from,const char *to,myf MyFlags); +extern int my_symlink(const char *content, const char *linkname, myf MyFlags); +extern size_t my_read(File Filedes,uchar *Buffer,size_t Count,myf MyFlags); +extern size_t my_pread(File Filedes,uchar *Buffer,size_t Count,my_off_t offset, + myf MyFlags); +extern int my_rename(const char *from,const char *to,myf MyFlags); +extern my_off_t my_seek(File fd,my_off_t pos,int whence,myf MyFlags); +extern my_off_t my_tell(File fd,myf MyFlags); +extern size_t my_write(File Filedes,const uchar *Buffer,size_t Count, + myf MyFlags); +extern size_t my_pwrite(File Filedes,const uchar *Buffer,size_t Count, + my_off_t offset,myf MyFlags); +extern size_t my_fread(FILE *stream,uchar *Buffer,size_t Count,myf MyFlags); +extern size_t my_fwrite(FILE *stream,const uchar *Buffer,size_t Count, + myf MyFlags); +extern my_off_t my_fseek(FILE *stream,my_off_t pos,int whence,myf MyFlags); +extern my_off_t my_ftell(FILE *stream,myf MyFlags); +extern void *_mymalloc(size_t uSize,const char *sFile, + uint uLine, myf MyFlag); +extern void *_myrealloc(void *pPtr,size_t uSize,const char *sFile, + uint uLine, myf MyFlag); +extern void * my_multi_malloc _VARARGS((myf MyFlags, ...)); +extern void _myfree(void *pPtr,const char *sFile,uint uLine, myf MyFlag); +extern int _sanity(const char *sFile, uint uLine); +extern void *_my_memdup(const void *from, size_t length, + const char *sFile, uint uLine,myf MyFlag); +extern char * _my_strdup(const char *from, const char *sFile, uint uLine, + myf MyFlag); +extern char *_my_strndup(const char *from, size_t length, + const char *sFile, uint uLine, + myf MyFlag); + +/* implemented in my_memmem.c */ +extern void *my_memmem(const void *haystack, size_t haystacklen, + const void *needle, size_t needlelen); + + +#ifdef _WIN32 +extern int my_access(const char *path, int amode); +#else +#define my_access access +#endif + +extern int check_if_legal_filename(const char *path); +extern int check_if_legal_tablename(const char *path); + +#ifdef _WIN32 +extern int nt_share_delete(const char *name,myf MyFlags); +#define my_delete_allow_opened(fname,flags) nt_share_delete((fname),(flags)) +#else +#define my_delete_allow_opened(fname,flags) my_delete((fname),(flags)) +#endif + +#ifdef _WIN32 +/* Windows-only functions (CRT equivalents)*/ +extern File my_sopen(const char *path, int oflag, int shflag, int pmode); +extern HANDLE my_get_osfhandle(File fd); +extern void my_osmaperr(unsigned long last_error); +#endif + +#ifndef TERMINATE +extern void TERMINATE(FILE *file, uint flag); +#endif +extern void init_glob_errs(void); +extern void wait_for_free_space(const char *filename, int errors); +extern FILE *my_fopen(const char *FileName,int Flags,myf MyFlags); +extern FILE *my_fdopen(File Filedes,const char *name, int Flags,myf MyFlags); +extern int my_fclose(FILE *fd,myf MyFlags); +extern File my_fileno(FILE *fd); +extern int my_chsize(File fd,my_off_t newlength, int filler, myf MyFlags); +extern int my_chmod(const char *name, mode_t mode, myf my_flags); +extern int my_sync(File fd, myf my_flags); +extern int my_sync_dir(const char *dir_name, myf my_flags); +extern int my_sync_dir_by_file(const char *file_name, myf my_flags); +extern void my_error _VARARGS((int nr,myf MyFlags, ...)); +extern void my_printf_error _VARARGS((uint my_err, const char *format, + myf MyFlags, ...)) + ATTRIBUTE_FORMAT(printf, 2, 4); +extern void my_printv_error(uint error, const char *format, myf MyFlags, + va_list ap); +extern int my_error_register(const char **errmsgs, int first, int last); +extern const char **my_error_unregister(int first, int last); +extern void my_message(uint my_err, const char *str,myf MyFlags); +extern void my_message_no_curses(uint my_err, const char *str,myf MyFlags); +extern my_bool my_init(void); +extern void my_end(int infoflag); +extern int my_redel(const char *from, const char *to, int MyFlags); +extern int my_copystat(const char *from, const char *to, int MyFlags); +extern char * my_filename(File fd); + +#ifndef THREAD +extern void dont_break(void); +extern void allow_break(void); +#else +#define dont_break() +#define allow_break() +#endif + +#ifdef EXTRA_DEBUG +void my_print_open_files(void); +#else +#define my_print_open_files() +#endif + +extern my_bool init_tmpdir(MY_TMPDIR *tmpdir, const char *pathlist); +extern char *my_tmpdir(MY_TMPDIR *tmpdir); +extern void free_tmpdir(MY_TMPDIR *tmpdir); + +extern void my_remember_signal(int signal_number,sig_handler (*func)(int)); +extern size_t dirname_part(char * to,const char *name, size_t *to_res_length); +extern size_t dirname_length(const char *name); +#define base_name(A) (A+dirname_length(A)) +extern int test_if_hard_path(const char *dir_name); +extern my_bool has_path(const char *name); +extern char *convert_dirname(char *to, const char *from, const char *from_end); +extern void to_unix_path(char * name); +extern char * fn_ext(const char *name); +extern char * fn_same(char * toname,const char *name,int flag); +extern char * fn_format(char * to,const char *name,const char *dir, + const char *form, uint flag); +extern size_t strlength(const char *str); +extern void pack_dirname(char * to,const char *from); +extern size_t normalize_dirname(char * to, const char *from); +extern size_t unpack_dirname(char * to,const char *from); +extern size_t cleanup_dirname(char * to,const char *from); +extern size_t system_filename(char * to,const char *from); +extern size_t unpack_filename(char * to,const char *from); +extern char * intern_filename(char * to,const char *from); +extern char * directory_file_name(char * dst, const char *src); +extern int pack_filename(char * to, const char *name, size_t max_length); +extern char * my_path(char * to,const char *progname, + const char *own_pathname_part); +extern char * my_load_path(char * to, const char *path, + const char *own_path_prefix); +extern int wild_compare(const char *str,const char *wildstr, + pbool str_is_pattern); +extern WF_PACK *wf_comp(char * str); +extern int wf_test(struct wild_file_pack *wf_pack,const char *name); +extern void wf_end(struct wild_file_pack *buffer); +extern size_t strip_sp(char * str); +extern my_bool array_append_string_unique(const char *str, + const char **array, size_t size); +extern void get_date(char * to,int timeflag,time_t use_time); +extern void soundex(CHARSET_INFO *, char * out_pntr, char * in_pntr, + pbool remove_garbage); +extern int init_record_cache(RECORD_CACHE *info,size_t cachesize,File file, + size_t reclength,enum cache_type type, + pbool use_async_io); +extern int read_cache_record(RECORD_CACHE *info,uchar *to); +extern int end_record_cache(RECORD_CACHE *info); +extern int write_cache_record(RECORD_CACHE *info,my_off_t filepos, + const uchar *record,size_t length); +extern int flush_write_cache(RECORD_CACHE *info); +extern long my_clock(void); +extern sig_handler sigtstp_handler(int signal_number); +extern void handle_recived_signals(void); + +extern sig_handler my_set_alarm_variable(int signo); +extern void my_string_ptr_sort(uchar *base,uint items,size_t size); +extern void radixsort_for_str_ptr(uchar* base[], uint number_of_elements, + size_t size_of_element,uchar *buffer[]); +extern qsort_t my_qsort(void *base_ptr, size_t total_elems, size_t size, + qsort_cmp cmp); +extern qsort_t my_qsort2(void *base_ptr, size_t total_elems, size_t size, + qsort2_cmp cmp, void *cmp_argument); +extern qsort2_cmp get_ptr_compare(size_t); +void my_store_ptr(uchar *buff, size_t pack_length, my_off_t pos); +my_off_t my_get_ptr(uchar *ptr, size_t pack_length); +extern int init_io_cache(IO_CACHE *info,File file,size_t cachesize, + enum cache_type type,my_off_t seek_offset, + pbool use_async_io, myf cache_myflags); +extern my_bool reinit_io_cache(IO_CACHE *info,enum cache_type type, + my_off_t seek_offset,pbool use_async_io, + pbool clear_cache); +extern void setup_io_cache(IO_CACHE* info); +extern int _my_b_read(IO_CACHE *info,uchar *Buffer,size_t Count); +#ifdef THREAD +extern int _my_b_read_r(IO_CACHE *info,uchar *Buffer,size_t Count); +extern void init_io_cache_share(IO_CACHE *read_cache, IO_CACHE_SHARE *cshare, + IO_CACHE *write_cache, uint num_threads); +extern void remove_io_thread(IO_CACHE *info); +#endif +extern int _my_b_seq_read(IO_CACHE *info,uchar *Buffer,size_t Count); +extern int _my_b_net_read(IO_CACHE *info,uchar *Buffer,size_t Count); +extern int _my_b_get(IO_CACHE *info); +extern int _my_b_async_read(IO_CACHE *info,uchar *Buffer,size_t Count); +extern int _my_b_write(IO_CACHE *info,const uchar *Buffer,size_t Count); +extern int my_b_append(IO_CACHE *info,const uchar *Buffer,size_t Count); +extern int my_b_safe_write(IO_CACHE *info,const uchar *Buffer,size_t Count); + +extern int my_block_write(IO_CACHE *info, const uchar *Buffer, + size_t Count, my_off_t pos); +extern int my_b_flush_io_cache(IO_CACHE *info, int need_append_buffer_lock); + +#define flush_io_cache(info) my_b_flush_io_cache((info),1) + +extern int end_io_cache(IO_CACHE *info); +extern size_t my_b_fill(IO_CACHE *info); +extern void my_b_seek(IO_CACHE *info,my_off_t pos); +extern size_t my_b_gets(IO_CACHE *info, char *to, size_t max_length); +extern my_off_t my_b_filelength(IO_CACHE *info); +extern size_t my_b_printf(IO_CACHE *info, const char* fmt, ...); +extern size_t my_b_vprintf(IO_CACHE *info, const char* fmt, va_list ap); +extern my_bool open_cached_file(IO_CACHE *cache,const char *dir, + const char *prefix, size_t cache_size, + myf cache_myflags); +extern my_bool real_open_cached_file(IO_CACHE *cache); +extern void close_cached_file(IO_CACHE *cache); +File create_temp_file(char *to, const char *dir, const char *pfx, + int mode, myf MyFlags); +#define my_init_dynamic_array(A,B,C,D) init_dynamic_array2(A,B,NULL,C,D CALLER_INFO) +#define my_init_dynamic_array_ci(A,B,C,D) init_dynamic_array2(A,B,NULL,C,D ORIG_CALLER_INFO) +#define my_init_dynamic_array2(A,B,C,D,E) init_dynamic_array2(A,B,C,D,E CALLER_INFO) +#define my_init_dynamic_array2_ci(A,B,C,D,E) init_dynamic_array2(A,B,C,D,E ORIG_CALLER_INFO) +extern my_bool init_dynamic_array2(DYNAMIC_ARRAY *array,uint element_size, + void *init_buffer, uint init_alloc, + uint alloc_increment + CALLER_INFO_PROTO); +/* init_dynamic_array() function is deprecated */ +extern my_bool init_dynamic_array(DYNAMIC_ARRAY *array,uint element_size, + uint init_alloc,uint alloc_increment + CALLER_INFO_PROTO); +extern my_bool insert_dynamic(DYNAMIC_ARRAY *array, const uchar * element); +extern uchar *alloc_dynamic(DYNAMIC_ARRAY *array); +extern uchar *pop_dynamic(DYNAMIC_ARRAY*); +extern my_bool set_dynamic(DYNAMIC_ARRAY *array,uchar * element,uint array_index); +extern my_bool allocate_dynamic(DYNAMIC_ARRAY *array, uint max_elements); +extern void get_dynamic(DYNAMIC_ARRAY *array,uchar * element,uint array_index); +extern void delete_dynamic(DYNAMIC_ARRAY *array); +extern void delete_dynamic_element(DYNAMIC_ARRAY *array, uint array_index); +extern void freeze_size(DYNAMIC_ARRAY *array); +extern int get_index_dynamic(DYNAMIC_ARRAY *array, uchar * element); +#define dynamic_array_ptr(array,array_index) ((array)->buffer+(array_index)*(array)->size_of_element) +#define dynamic_element(array,array_index,type) ((type)((array)->buffer) +(array_index)) +#define push_dynamic(A,B) insert_dynamic((A),(B)) +#define reset_dynamic(array) ((array)->elements= 0) +#define sort_dynamic(A,cmp) my_qsort((A)->buffer, (A)->elements, (A)->size_of_element, (cmp)) + +extern my_bool init_dynamic_string(DYNAMIC_STRING *str, const char *init_str, + size_t init_alloc,size_t alloc_increment); +extern my_bool dynstr_append(DYNAMIC_STRING *str, const char *append); +my_bool dynstr_append_mem(DYNAMIC_STRING *str, const char *append, + size_t length); +extern my_bool dynstr_append_os_quoted(DYNAMIC_STRING *str, const char *append, + ...); +extern my_bool dynstr_set(DYNAMIC_STRING *str, const char *init_str); +extern my_bool dynstr_realloc(DYNAMIC_STRING *str, size_t additional_size); +extern my_bool dynstr_trunc(DYNAMIC_STRING *str, size_t n); +extern void dynstr_free(DYNAMIC_STRING *str); +#ifdef HAVE_MLOCK +extern void *my_malloc_lock(size_t length,myf flags); +extern void my_free_lock(void *ptr,myf flags); +#else +#define my_malloc_lock(A,B) my_malloc((A),(B)) +#define my_free_lock(A,B) my_free((A),(B)) +#endif +#define alloc_root_inited(A) ((A)->min_malloc != 0) +#define ALLOC_ROOT_MIN_BLOCK_SIZE (MALLOC_OVERHEAD + sizeof(USED_MEM) + 8) +#define clear_alloc_root(A) do { (A)->free= (A)->used= (A)->pre_alloc= 0; (A)->min_malloc=0;} while(0) +extern void init_alloc_root(MEM_ROOT *mem_root, size_t block_size, + size_t pre_alloc_size); +extern void *alloc_root(MEM_ROOT *mem_root, size_t Size); +extern void *multi_alloc_root(MEM_ROOT *mem_root, ...); +extern void free_root(MEM_ROOT *root, myf MyFLAGS); +extern void set_prealloc_root(MEM_ROOT *root, char *ptr); +extern void reset_root_defaults(MEM_ROOT *mem_root, size_t block_size, + size_t prealloc_size); +extern char *strdup_root(MEM_ROOT *root,const char *str); +extern char *strmake_root(MEM_ROOT *root,const char *str,size_t len); +extern void *memdup_root(MEM_ROOT *root,const void *str, size_t len); +extern int get_defaults_options(int argc, char **argv, + char **defaults, char **extra_defaults, + char **group_suffix); +extern const char *args_separator; +extern int my_load_defaults(const char *conf_file, const char **groups, + int *argc, char ***argv, const char ***); +extern int load_defaults(const char *conf_file, const char **groups, + int *argc, char ***argv); +extern int modify_defaults_file(const char *file_location, const char *option, + const char *option_value, + const char *section_name, int remove_option); +extern int my_search_option_files(const char *conf_file, int *argc, + char ***argv, uint *args_used, + Process_option_func func, void *func_ctx, + const char **default_directories); +extern void free_defaults(char **argv); +extern void my_print_default_files(const char *conf_file); +extern void print_defaults(const char *conf_file, const char **groups); +extern my_bool my_compress(uchar *, size_t *, size_t *); +extern my_bool my_uncompress(uchar *, size_t , size_t *); +extern uchar *my_compress_alloc(const uchar *packet, size_t *len, + size_t *complen); +extern int packfrm(uchar *, size_t, uchar **, size_t *); +extern int unpackfrm(uchar **, size_t *, const uchar *); + +extern ha_checksum my_checksum(ha_checksum crc, const uchar *mem, + size_t count); +#ifndef DBUG_OFF +extern void my_debug_put_break_here(void); +#else +#define my_debug_put_break_here() do {} while(0) +#endif + +extern void my_sleep(ulong m_seconds); +extern ulong crc32(ulong crc, const uchar *buf, uint len); +extern uint my_set_max_open_files(uint files); +void my_free_open_file_info(void); + +extern time_t my_time(myf flags); +extern ulonglong my_getsystime(void); +extern ulonglong my_micro_time(); +extern ulonglong my_micro_time_and_time(time_t *time_arg); +time_t my_time_possible_from_micro(ulonglong microtime); +extern my_bool my_gethwaddr(uchar *to); +extern int my_getncpus(); + +#ifdef HAVE_SYS_MMAN_H +#include + +#ifndef MAP_NOSYNC +#define MAP_NOSYNC 0 +#endif +#ifndef MAP_NORESERVE +#define MAP_NORESERVE 0 /* For irix and AIX */ +#endif + +#ifdef HAVE_MMAP64 +#define my_mmap(a,b,c,d,e,f) mmap64(a,b,c,d,e,f) +#else +#define my_mmap(a,b,c,d,e,f) mmap(a,b,c,d,e,f) +#endif +#define my_munmap(a,b) munmap((a),(b)) + +#else +/* not a complete set of mmap() flags, but only those that nesessary */ +#define PROT_READ 1 +#define PROT_WRITE 2 +#define MAP_NORESERVE 0 +#define MAP_SHARED 0x0001 +#define MAP_PRIVATE 0x0002 +#define MAP_NOSYNC 0x0800 +#define MAP_FAILED ((void *)-1) +#define MS_SYNC 0x0000 + +#ifndef __NETWARE__ +#define HAVE_MMAP +#endif + +void *my_mmap(void *, size_t, int, int, int, my_off_t); +int my_munmap(void *, size_t); +#endif + +/* my_getpagesize */ +#ifdef HAVE_GETPAGESIZE +#define my_getpagesize() getpagesize() +#else +int my_getpagesize(void); +#endif + +int my_msync(int, void *, size_t, int); + +#define MY_UUID_SIZE 16 +#define MY_UUID_STRING_LENGTH (8+1+4+1+4+1+4+1+12) + +void my_uuid_init(ulong seed1, ulong seed2); +void my_uuid(uchar *guid); +void my_uuid2str(const uchar *guid, char *s); +void my_uuid_end(); + +struct my_rnd_struct { + unsigned long seed1,seed2,max_value; + double max_value_dbl; +}; + +void my_rnd_init(struct my_rnd_struct *rand_st, ulong seed1, ulong seed2); +double my_rnd(struct my_rnd_struct *rand_st); + +/* character sets */ +extern uint get_charset_number(const char *cs_name, uint cs_flags); +extern uint get_collation_number(const char *name); +extern const char *get_charset_name(uint cs_number); + +extern CHARSET_INFO *get_charset(uint cs_number, myf flags); +extern CHARSET_INFO *get_charset_by_name(const char *cs_name, myf flags); +extern CHARSET_INFO *get_charset_by_csname(const char *cs_name, + uint cs_flags, myf my_flags); + +extern my_bool resolve_charset(const char *cs_name, + CHARSET_INFO *default_cs, + CHARSET_INFO **cs); +extern my_bool resolve_collation(const char *cl_name, + CHARSET_INFO *default_cl, + CHARSET_INFO **cl); + +extern void free_charsets(void); +extern char *get_charsets_dir(char *buf); +extern my_bool my_charset_same(CHARSET_INFO *cs1, CHARSET_INFO *cs2); +extern my_bool init_compiled_charsets(myf flags); +extern void add_compiled_collation(CHARSET_INFO *cs); +extern size_t escape_string_for_mysql(CHARSET_INFO *charset_info, + char *to, size_t to_length, + const char *from, size_t length); +#ifdef __WIN__ +#define BACKSLASH_MBTAIL +/* File system character set */ +extern CHARSET_INFO *fs_character_set(void); +#endif +extern size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info, + char *to, size_t to_length, + const char *from, size_t length); + +extern void thd_increment_bytes_sent(ulong length); +extern void thd_increment_bytes_received(ulong length); +extern void thd_increment_net_big_packet_count(ulong length); + +#ifdef __WIN__ +extern my_bool have_tcpip; /* Is set if tcpip is used */ + +/* implemented in my_windac.c */ + +int my_security_attr_create(SECURITY_ATTRIBUTES **psa, const char **perror, + DWORD owner_rights, DWORD everybody_rights); + +void my_security_attr_free(SECURITY_ATTRIBUTES *sa); + +/* implemented in my_conio.c */ +char* my_cgets(char *string, size_t clen, size_t* plen); + +#endif +#ifdef __NETWARE__ +void netware_reg_user(const char *ip, const char *user, + const char *application); +#endif + +C_MODE_END +#endif /* _my_sys_h */ diff --git a/mysql_incl/my_time.h b/mysql_incl/my_time.h new file mode 100644 index 0000000..58995f1 --- /dev/null +++ b/mysql_incl/my_time.h @@ -0,0 +1,172 @@ +/* Copyright (C) 2004-2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + This is a private header of sql-common library, containing + declarations for my_time.c +*/ + +#ifndef _my_time_h_ +#define _my_time_h_ +#include "my_global.h" +#include "mysql_time.h" + +C_MODE_START + +extern ulonglong log_10_int[20]; +extern uchar days_in_month[]; + +/* + Portable time_t replacement. + Should be signed and hold seconds for 1902 -- 2038-01-19 range + i.e at least a 32bit variable + + Using the system built in time_t is not an option as + we rely on the above requirements in the time functions + + For example QNX has an unsigned time_t type +*/ +typedef long my_time_t; + +#define MY_TIME_T_MAX LONG_MAX +#define MY_TIME_T_MIN LONG_MIN + +/* Time handling defaults */ +#define TIMESTAMP_MAX_YEAR 2038 +#define TIMESTAMP_MIN_YEAR (1900 + YY_PART_YEAR - 1) +#define TIMESTAMP_MAX_VALUE INT_MAX32 +#define TIMESTAMP_MIN_VALUE 1 + +/* two-digit years < this are 20..; >= this are 19.. */ +#define YY_PART_YEAR 70 + +/* Flags to str_to_datetime */ +#define TIME_FUZZY_DATE 1 +#define TIME_DATETIME_ONLY 2 +/* Must be same as MODE_NO_ZERO_IN_DATE */ +#define TIME_NO_ZERO_IN_DATE (65536L*2*2*2*2*2*2*2) +/* Must be same as MODE_NO_ZERO_DATE */ +#define TIME_NO_ZERO_DATE (TIME_NO_ZERO_IN_DATE*2) +#define TIME_INVALID_DATES (TIME_NO_ZERO_DATE*2) + +#define MYSQL_TIME_WARN_TRUNCATED 1 +#define MYSQL_TIME_WARN_OUT_OF_RANGE 2 + +/* Limits for the TIME data type */ +#define TIME_MAX_HOUR 838 +#define TIME_MAX_MINUTE 59 +#define TIME_MAX_SECOND 59 +#define TIME_MAX_VALUE (TIME_MAX_HOUR*10000 + TIME_MAX_MINUTE*100 + \ + TIME_MAX_SECOND) +#define TIME_MAX_VALUE_SECONDS (TIME_MAX_HOUR * 3600L + \ + TIME_MAX_MINUTE * 60L + TIME_MAX_SECOND) + +my_bool check_date(const MYSQL_TIME *ltime, my_bool not_zero_date, + ulong flags, int *was_cut); +enum enum_mysql_timestamp_type +str_to_datetime(const char *str, uint length, MYSQL_TIME *l_time, + uint flags, int *was_cut); +longlong number_to_datetime(longlong nr, MYSQL_TIME *time_res, + uint flags, int *was_cut); +ulonglong TIME_to_ulonglong_datetime(const MYSQL_TIME *); +ulonglong TIME_to_ulonglong_date(const MYSQL_TIME *); +ulonglong TIME_to_ulonglong_time(const MYSQL_TIME *); +ulonglong TIME_to_ulonglong(const MYSQL_TIME *); + + +my_bool str_to_time(const char *str,uint length, MYSQL_TIME *l_time, + int *warning); + +int check_time_range(struct st_mysql_time *, int *warning); + +long calc_daynr(uint year,uint month,uint day); +uint calc_days_in_year(uint year); +uint year_2000_handling(uint year); + +void my_init_time(void); + + +/* + Function to check sanity of a TIMESTAMP value + + DESCRIPTION + Check if a given MYSQL_TIME value fits in TIMESTAMP range. + This function doesn't make precise check, but rather a rough + estimate. + + RETURN VALUES + FALSE The value seems sane + TRUE The MYSQL_TIME value is definitely out of range +*/ + +static inline my_bool validate_timestamp_range(const MYSQL_TIME *t) +{ + if ((t->year > TIMESTAMP_MAX_YEAR || t->year < TIMESTAMP_MIN_YEAR) || + (t->year == TIMESTAMP_MAX_YEAR && (t->month > 1 || t->day > 19)) || + (t->year == TIMESTAMP_MIN_YEAR && (t->month < 12 || t->day < 31))) + return FALSE; + + return TRUE; +} + +my_time_t +my_system_gmt_sec(const MYSQL_TIME *t, long *my_timezone, + my_bool *in_dst_time_gap); + +void set_zero_time(MYSQL_TIME *tm, enum enum_mysql_timestamp_type time_type); + +/* + Required buffer length for my_time_to_str, my_date_to_str, + my_datetime_to_str and TIME_to_string functions. Note, that the + caller is still responsible to check that given TIME structure + has values in valid ranges, otherwise size of the buffer could + be not enough. We also rely on the fact that even wrong values + sent using binary protocol fit in this buffer. +*/ +#define MAX_DATE_STRING_REP_LENGTH 30 + +int my_time_to_str(const MYSQL_TIME *l_time, char *to); +int my_date_to_str(const MYSQL_TIME *l_time, char *to); +int my_datetime_to_str(const MYSQL_TIME *l_time, char *to); +int my_TIME_to_str(const MYSQL_TIME *l_time, char *to); + +/* + Available interval types used in any statement. + + 'interval_type' must be sorted so that simple intervals comes first, + ie year, quarter, month, week, day, hour, etc. The order based on + interval size is also important and the intervals should be kept in a + large to smaller order. (get_interval_value() depends on this) + + Note: If you change the order of elements in this enum you should fix + order of elements in 'interval_type_to_name' and 'interval_names' + arrays + + See also interval_type_to_name, get_interval_value, interval_names +*/ + +enum interval_type +{ + INTERVAL_YEAR, INTERVAL_QUARTER, INTERVAL_MONTH, INTERVAL_WEEK, INTERVAL_DAY, + INTERVAL_HOUR, INTERVAL_MINUTE, INTERVAL_SECOND, INTERVAL_MICROSECOND, + INTERVAL_YEAR_MONTH, INTERVAL_DAY_HOUR, INTERVAL_DAY_MINUTE, + INTERVAL_DAY_SECOND, INTERVAL_HOUR_MINUTE, INTERVAL_HOUR_SECOND, + INTERVAL_MINUTE_SECOND, INTERVAL_DAY_MICROSECOND, INTERVAL_HOUR_MICROSECOND, + INTERVAL_MINUTE_MICROSECOND, INTERVAL_SECOND_MICROSECOND, INTERVAL_LAST +}; + +C_MODE_END + +#endif /* _my_time_h_ */ diff --git a/mysql_incl/my_tree.h b/mysql_incl/my_tree.h new file mode 100644 index 0000000..e387b25 --- /dev/null +++ b/mysql_incl/my_tree.h @@ -0,0 +1,96 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _tree_h +#define _tree_h +#ifdef __cplusplus +extern "C" { +#endif + +#include "my_base.h" /* get 'enum ha_rkey_function' */ + +/* Worst case tree is half full. This gives use 2^(MAX_TREE_HEIGHT/2) leafs */ +#define MAX_TREE_HEIGHT 64 + +#define ELEMENT_KEY(tree,element)\ +(tree->offset_to_key ? (void*)((uchar*) element+tree->offset_to_key) :\ + *((void**) (element+1))) + +#define tree_set_pointer(element,ptr) *((uchar **) (element+1))=((uchar*) (ptr)) + +#define TREE_NO_DUPS 1 + +typedef enum { left_root_right, right_root_left } TREE_WALK; +typedef uint32 element_count; +typedef int (*tree_walk_action)(void *,element_count,void *); + +typedef enum { free_init, free_free, free_end } TREE_FREE; +typedef void (*tree_element_free)(void*, TREE_FREE, void *); + +typedef struct st_tree_element { + struct st_tree_element *left,*right; + uint32 count:31, + colour:1; /* black is marked as 1 */ +} TREE_ELEMENT; + +#define ELEMENT_CHILD(element, offs) (*(TREE_ELEMENT**)((char*)element + offs)) + +typedef struct st_tree { + TREE_ELEMENT *root,null_element; + TREE_ELEMENT **parents[MAX_TREE_HEIGHT]; + uint offset_to_key,elements_in_tree,size_of_element; + ulong memory_limit, allocated; + qsort_cmp2 compare; + void *custom_arg; + MEM_ROOT mem_root; + my_bool with_delete; + tree_element_free free; + uint flag; +} TREE; + + /* Functions on whole tree */ +void init_tree(TREE *tree, ulong default_alloc_size, ulong memory_limit, + int size, qsort_cmp2 compare, my_bool with_delete, + tree_element_free free_element, void *custom_arg); +void delete_tree(TREE*); +void reset_tree(TREE*); + + /* similar to delete tree, except we do not my_free() blocks in mem_root */ +#define is_tree_inited(tree) ((tree)->root != 0) + + /* Functions on leafs */ +TREE_ELEMENT *tree_insert(TREE *tree,void *key, uint key_size, + void *custom_arg); +void *tree_search(TREE *tree, void *key, void *custom_arg); +int tree_walk(TREE *tree,tree_walk_action action, + void *argument, TREE_WALK visit); +int tree_delete(TREE *tree, void *key, uint key_size, void *custom_arg); +void *tree_search_key(TREE *tree, const void *key, + TREE_ELEMENT **parents, TREE_ELEMENT ***last_pos, + enum ha_rkey_function flag, void *custom_arg); +void *tree_search_edge(TREE *tree, TREE_ELEMENT **parents, + TREE_ELEMENT ***last_pos, int child_offs); +void *tree_search_next(TREE *tree, TREE_ELEMENT ***last_pos, int l_offs, + int r_offs); +ha_rows tree_record_pos(TREE *tree, const void *key, + enum ha_rkey_function search_flag, void *custom_arg); +#define reset_free_element(tree) (tree)->free= 0 + +#define TREE_ELEMENT_EXTRA_SIZE (sizeof(TREE_ELEMENT) + sizeof(void*)) + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/my_trie.h b/mysql_incl/my_trie.h new file mode 100644 index 0000000..72dd485 --- /dev/null +++ b/mysql_incl/my_trie.h @@ -0,0 +1,141 @@ +/* Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _trie_h +#define _trie_h +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct st_trie_node +{ + uint16 leaf; /* Depth from root node if match, 0 else */ + uchar c; /* Label on this edge */ + struct st_trie_node *next; /* Next label */ + struct st_trie_node *links; /* Array of edges leaving this node */ + struct st_trie_node *fail; /* AC failure function */ +} TRIE_NODE; + +typedef struct st_trie +{ + TRIE_NODE root; + MEM_ROOT mem_root; + CHARSET_INFO *charset; + uint32 nnodes; + uint32 nwords; +} TRIE; + +typedef struct st_ac_trie_state +{ + TRIE *trie; + TRIE_NODE *node; +} AC_TRIE_STATE; + +extern TRIE *trie_init (TRIE *trie, CHARSET_INFO *charset); +extern void trie_free (TRIE *trie); +extern my_bool trie_insert (TRIE *trie, const uchar *key, uint keylen); +extern my_bool ac_trie_prepare (TRIE *trie); +extern void ac_trie_init (TRIE *trie, AC_TRIE_STATE *state); + + +/* `trie_goto' is internal function and shouldn't be used. */ + +static inline TRIE_NODE *trie_goto (TRIE_NODE *root, TRIE_NODE *node, uchar c) +{ + TRIE_NODE *next; + DBUG_ENTER("trie_goto"); + for (next= node->links; next; next= next->next) + if (next->c == c) + DBUG_RETURN(next); + if (root == node) + DBUG_RETURN(root); + DBUG_RETURN(NULL); +} + + +/* + SYNOPSIS + int ac_trie_next (AC_TRIE_STATE *state, uchar *c); + state - valid pointer to `AC_TRIE_STATE' + c - character to lookup + + DESCRIPTION + Implementation of search using Aho-Corasick automaton. + Performs char-by-char search. + + RETURN VALUE + `ac_trie_next' returns length of matched word or 0. +*/ + +static inline int ac_trie_next (AC_TRIE_STATE *state, uchar *c) +{ + TRIE_NODE *root, *node; + DBUG_ENTER("ac_trie_next"); + DBUG_ASSERT(state && c); + root= &state->trie->root; + node= state->node; + while (! (state->node= trie_goto(root, node, *c))) + node= node->fail; + DBUG_RETURN(state->node->leaf); +} + + +/* + SYNOPSIS + my_bool trie_search (TRIE *trie, const uchar *key, uint keylen); + trie - valid pointer to `TRIE' + key - valid pointer to key to insert + keylen - non-0 key length + + DESCRIPTION + Performs key lookup in trie. + + RETURN VALUE + `trie_search' returns `true' if key is in `trie'. Otherwise, + `false' is returned. + + NOTES + Consecutive search here is "best by test". arrays are very short, so + binary search or hashing would add too much complexity that would + overweight speed gain. Especially because compiler can optimize simple + consecutive loop better (tested) +*/ + +static inline my_bool trie_search (TRIE *trie, const uchar *key, uint keylen) +{ + TRIE_NODE *node; + uint k; + DBUG_ENTER("trie_search"); + DBUG_ASSERT(trie && key && keylen); + node= &trie->root; + + for (k= 0; k < keylen; k++) + { + uchar p; + if (! (node= node->links)) + DBUG_RETURN(FALSE); + p= key[k]; + while (p != node->c) + if (! (node= node->next)) + DBUG_RETURN(FALSE); + } + + DBUG_RETURN(node->leaf > 0); +} + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/my_uctype.h b/mysql_incl/my_uctype.h new file mode 100644 index 0000000..9aaf478 --- /dev/null +++ b/mysql_incl/my_uctype.h @@ -0,0 +1,1479 @@ +/* Copyright (C) 2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ + +/* + Unicode ctype data + Generated from UnicodeData-5.0.0d9.txt +*/ +static unsigned char uctype_page00[256]= +{ + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, + 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, + 16, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, + 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 16, 16, 16, 16, 16, + 16, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, + 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 16, 16, 16, 16, 32, + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, + 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 16, 16, 32, 16, 16, + 16, 16, 20, 20, 16, 2, 16, 16, 16, 20, 2, 16, 20, 20, 20, 16, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 16, 1, 1, 1, 1, 1, 1, 1, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2, 2, 2, 2, 2 +}; + +static unsigned char uctype_page01[256]= +{ + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2, 2, + 2, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 1, 1, + 1, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 1, + 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, + 2, 1, 1, 1, 2, 1, 2, 1, 1, 2, 2, 2, 1, 2, 2, 2, + 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 2, 1, + 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 2, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2 +}; + +static unsigned char uctype_page02[256]= +{ + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, + 2, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 2, 2, 2, 2, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 +}; + +static unsigned char uctype_page03[256]= +{ + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 2, 2, 2, 2, 16, 0, + 0, 0, 0, 0, 16, 16, 1, 16, 1, 1, 1, 0, 1, 0, 1, 1, + 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, + 2, 2, 1, 1, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 2, 2, 2, 2, 1, 2, 16, 1, 2, 1, 1, 2, 2, 1, 1, 1 +}; + +static unsigned char uctype_page04[256]= +{ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 16, 18, 18, 18, 18, 0, 18, 18, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 +}; + +static unsigned char uctype_page05[256]= +{ + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 16, 16, 16, 16, 16, 16, + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 0, 16, 16, 0, 0, 0, 0, 0, + 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 16, 18, + 16, 18, 18, 16, 18, 18, 16, 18, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, + 2, 2, 2, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page06[256]= +{ + 32, 32, 32, 32, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, + 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 16, 0, 0, 16, 16, + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 2, 2, + 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 16, 2, 18, 18, 18, 18, 18, 18, 18, 32, 18, 18, + 18, 18, 18, 18, 18, 2, 2, 18, 18, 16, 18, 18, 18, 18, 2, 2, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 16, 16, 2 +}; + +static unsigned char uctype_page07[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 32, + 2, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 2, 2, 16, 16, 16, 16, 2, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page09[256]= +{ + 0, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, + 2, 18, 18, 18, 18, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 18, 18, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, + 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, + 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, + 2, 0, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, + 18, 18, 18, 18, 18, 0, 0, 18, 18, 0, 0, 18, 18, 18, 2, 0, + 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 2, 2, 0, 2, + 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 2, 2, 16, 16, 20, 20, 20, 20, 20, 20, 16, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page0A[256]= +{ + 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, + 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, + 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 0, 0, 18, 0, 18, 18, + 18, 18, 18, 0, 0, 0, 0, 18, 18, 0, 0, 18, 18, 18, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 0, + 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 18, 18, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, + 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, + 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, + 18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 0, 0, + 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page0B[256]= +{ + 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, + 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, + 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, + 18, 18, 18, 18, 0, 0, 0, 18, 18, 0, 0, 18, 18, 18, 0, 0, + 0, 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 2, 2, 0, 2, + 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 18, 2, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, + 2, 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 0, 2, 0, 2, 2, + 0, 0, 0, 2, 2, 0, 0, 0, 2, 2, 2, 0, 0, 0, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, + 18, 18, 18, 0, 0, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page0C[256]= +{ + 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, + 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, + 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, + 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, + 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, + 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, + 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 2, 0, + 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page0D[256]= +{ + 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, + 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, + 18, 18, 18, 18, 0, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 18, 0, 0, 0, 0, 18, + 18, 18, 18, 18, 18, 0, 18, 0, 18, 18, 18, 18, 18, 18, 18, 18, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 18, 18, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page0E[256]= +{ + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 18, 2, 2, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 16, + 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 16, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 2, 0, 2, 0, 0, 2, 2, 0, 2, 0, 0, 2, 0, 0, + 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, + 0, 2, 2, 2, 0, 2, 0, 2, 0, 0, 2, 2, 0, 2, 2, 2, + 2, 18, 2, 2, 18, 18, 18, 18, 18, 18, 0, 18, 18, 2, 0, 0, + 2, 2, 2, 2, 2, 0, 2, 0, 18, 18, 18, 18, 18, 18, 0, 0, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 2, 2, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page0F[256]= +{ + 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 16, 16, 16, 16, 16, 16, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 16, 18, 16, 18, 16, 18, 16, 16, 16, 16, 18, 18, + 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, + 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 16, 18, 18, 2, 2, 2, 2, 0, 0, 0, 0, + 18, 18, 18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 16, 16, + 16, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 16, 16, 0, 0, 16, + 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page10[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 2, 0, 18, 18, 18, 18, + 18, 18, 18, 0, 0, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, + 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 0, 0, 0 +}; + +static unsigned char uctype_page11[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page12[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, + 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 +}; + +static unsigned char uctype_page13[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page14[256]= +{ + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 +}; + +static unsigned char uctype_page16[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 2, + 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 7, 7, + 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page17[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, + 2, 2, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 18, 18, 18, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, + 2, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 32, 32, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 16, 16, 16, 2, 16, 16, 16, 16, 2, 18, 0, 0, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page18[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 8, 0, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page19[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, + 16, 0, 0, 0, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, + 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 2, 2, 2, 2, 2, 2, 2, 18, 18, 0, 0, 0, 0, 0, 0, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 +}; + +static unsigned char uctype_page1A[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 0, 0, 16, 16, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page1B[256]= +{ + 18, 18, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page1D[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18 +}; + +static unsigned char uctype_page1E[256]= +{ + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page1F[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 0, 1, 0, 1, 0, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 2, 16, + 16, 16, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 16, 16, + 2, 2, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1, 0, 16, 16, 16, + 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 16, 16, 16, + 0, 0, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 16, 0 +}; + +static unsigned char uctype_page20[256]= +{ + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 32, 32, 32, 32, 32, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 8, 8, 32, 32, 32, 32, 32, 8, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 8, + 32, 32, 32, 32, 0, 0, 0, 0, 0, 0, 32, 32, 32, 32, 32, 32, + 20, 2, 0, 0, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 2, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 0, + 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page21[256]= +{ + 16, 16, 1, 16, 16, 16, 16, 1, 16, 16, 2, 1, 1, 1, 2, 2, + 1, 1, 1, 2, 16, 1, 16, 16, 16, 1, 1, 1, 1, 1, 16, 16, + 16, 16, 16, 16, 1, 16, 1, 16, 1, 16, 1, 1, 1, 1, 16, 2, + 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 16, 16, 2, 2, 1, 1, + 16, 16, 16, 16, 16, 1, 2, 2, 2, 2, 16, 16, 16, 16, 2, 0, + 0, 0, 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 +}; + +static unsigned char uctype_page23[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page24[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 +}; + +static unsigned char uctype_page26[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page27[256]= +{ + 0, 16, 16, 16, 16, 0, 16, 16, 16, 16, 0, 0, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 0, 16, + 16, 16, 16, 0, 0, 0, 16, 0, 16, 16, 16, 16, 16, 16, 16, 0, + 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 16, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 +}; + +static unsigned char uctype_page2B[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page2C[256]= +{ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, + 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 0, 0, 0, + 0, 0, 0, 0, 2, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 2, 1, 2, 2, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 20, 16, 16 +}; + +static unsigned char uctype_page2D[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, + 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, + 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, + 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page2E[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_page2F[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0 +}; + +static unsigned char uctype_page30[256]= +{ + 8, 16, 16, 16, 16, 2, 2, 7, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 7, 7, 7, 7, 7, 7, 7, 7, 7, 18, 18, 18, 18, 18, 18, + 16, 2, 2, 2, 2, 2, 16, 16, 7, 7, 7, 2, 2, 16, 16, 16, + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 0, 0, 18, 18, 16, 16, 2, 2, 2, + 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2 +}; + +static unsigned char uctype_page31[256]= +{ + 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, + 16, 16, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 +}; + +static unsigned char uctype_page32[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0 +}; + +static unsigned char uctype_page4D[256]= +{ + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 +}; + +static unsigned char uctype_page9F[256]= +{ + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageA4[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageA7[256]= +{ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 0, 0, 0, 0, 0, + 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageA8[256]= +{ + 2, 2, 18, 2, 2, 2, 18, 2, 2, 2, 2, 18, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 18, 18, 18, 18, 18, 16, 16, 16, 16, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageD7[256]= +{ + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageD8[256]= +{ + 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageDB[256]= +{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, + 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 +}; + +static unsigned char uctype_pageDC[256]= +{ + 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageDF[256]= +{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 +}; + +static unsigned char uctype_pageE0[256]= +{ + 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageF8[256]= +{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 +}; + +static unsigned char uctype_pageFA[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static unsigned char uctype_pageFB[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 18, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 0, + 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 +}; + +static unsigned char uctype_pageFD[256]= +{ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 0, 0 +}; + +static unsigned char uctype_pageFE[256]= +{ + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, + 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 32 +}; + +static unsigned char uctype_pageFF[256]= +{ + 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, + 16, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 16, 16, 16, 16, 16, + 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, + 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, + 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 0, 0, 0, + 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 32, 32, 16, 16, 0, 0 +}; + +MY_UNI_CTYPE my_uni_ctype[256]={ + {0,uctype_page00}, + {0,uctype_page01}, + {0,uctype_page02}, + {0,uctype_page03}, + {0,uctype_page04}, + {0,uctype_page05}, + {0,uctype_page06}, + {0,uctype_page07}, + {0,NULL}, + {0,uctype_page09}, + {0,uctype_page0A}, + {0,uctype_page0B}, + {0,uctype_page0C}, + {0,uctype_page0D}, + {0,uctype_page0E}, + {0,uctype_page0F}, + {0,uctype_page10}, + {0,uctype_page11}, + {0,uctype_page12}, + {0,uctype_page13}, + {0,uctype_page14}, + {2,NULL}, + {0,uctype_page16}, + {0,uctype_page17}, + {0,uctype_page18}, + {0,uctype_page19}, + {0,uctype_page1A}, + {0,uctype_page1B}, + {0,NULL}, + {0,uctype_page1D}, + {0,uctype_page1E}, + {0,uctype_page1F}, + {0,uctype_page20}, + {0,uctype_page21}, + {16,NULL}, + {0,uctype_page23}, + {0,uctype_page24}, + {16,NULL}, + {0,uctype_page26}, + {0,uctype_page27}, + {16,NULL}, + {16,NULL}, + {16,NULL}, + {0,uctype_page2B}, + {0,uctype_page2C}, + {0,uctype_page2D}, + {0,uctype_page2E}, + {0,uctype_page2F}, + {0,uctype_page30}, + {0,uctype_page31}, + {0,uctype_page32}, + {16,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {0,uctype_page4D}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {0,uctype_page9F}, + {2,NULL}, + {2,NULL}, + {2,NULL}, + {2,NULL}, + {0,uctype_pageA4}, + {0,NULL}, + {0,NULL}, + {0,uctype_pageA7}, + {0,uctype_pageA8}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {3,NULL}, + {0,uctype_pageD7}, + {0,uctype_pageD8}, + {0,NULL}, + {0,NULL}, + {0,uctype_pageDB}, + {0,uctype_pageDC}, + {0,NULL}, + {0,NULL}, + {0,uctype_pageDF}, + {0,uctype_pageE0}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,NULL}, + {0,uctype_pageF8}, + {2,NULL}, + {0,uctype_pageFA}, + {0,uctype_pageFB}, + {2,NULL}, + {0,uctype_pageFD}, + {0,uctype_pageFE}, + {0,uctype_pageFF} +}; + + diff --git a/mysql_incl/my_vle.h b/mysql_incl/my_vle.h new file mode 100644 index 0000000..c09f822 --- /dev/null +++ b/mysql_incl/my_vle.h @@ -0,0 +1,38 @@ +/* Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef VLE_H +#define VLE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "my_global.h" + +/* + The size (in bytes) required to store the object ITEM, which can be + either an expression or a type (since sizeof() is used on the item). +*/ +#define my_vle_sizeof(ITEM) (((sizeof(ITEM) * CHAR_BIT) + 6) / 7) + +uchar *my_vle_encode(uchar *vle, size_t max, ulong value); +uchar const *my_vle_decode(ulong *value_ptr, uchar const *vle); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/mysql_incl/my_xml.h b/mysql_incl/my_xml.h new file mode 100644 index 0000000..6a453ee --- /dev/null +++ b/mysql_incl/my_xml.h @@ -0,0 +1,89 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +#ifndef _my_xml_h +#define _my_xml_h + +#ifdef __cplusplus +extern "C" { +#endif + + +#define MY_XML_OK 0 +#define MY_XML_ERROR 1 + +/* + A flag whether to use absolute tag names in call-back functions, + like "a", "a.b" and "a.b.c" (used in character set file parser), + or relative names like "a", "b" and "c". +*/ +#define MY_XML_FLAG_RELATIVE_NAMES 1 + +/* + A flag whether to skip normilization of text values before calling + call-back functions: i.e. skip leading/trailing spaces, + \r, \n, \t characters. +*/ +#define MY_XML_FLAG_SKIP_TEXT_NORMALIZATION 2 + +enum my_xml_node_type +{ + MY_XML_NODE_TAG, /* can have TAG, ATTR and TEXT children */ + MY_XML_NODE_ATTR, /* can have TEXT children */ + MY_XML_NODE_TEXT /* cannot have children */ +}; + +typedef struct xml_stack_st +{ + int flags; + enum my_xml_node_type current_node_type; + char errstr[128]; + char attr[128]; + char *attrend; + const char *beg; + const char *cur; + const char *end; + void *user_data; + int (*enter)(struct xml_stack_st *st,const char *val, size_t len); + int (*value)(struct xml_stack_st *st,const char *val, size_t len); + int (*leave_xml)(struct xml_stack_st *st,const char *val, size_t len); +} MY_XML_PARSER; + +void my_xml_parser_create(MY_XML_PARSER *st); +void my_xml_parser_free(MY_XML_PARSER *st); +int my_xml_parse(MY_XML_PARSER *st,const char *str, size_t len); + +void my_xml_set_value_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, + const char *, + size_t len)); +void my_xml_set_enter_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, + const char *, + size_t len)); +void my_xml_set_leave_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, + const char *, + size_t len)); +void my_xml_set_user_data(MY_XML_PARSER *st, void *); + +size_t my_xml_error_pos(MY_XML_PARSER *st); +uint my_xml_error_lineno(MY_XML_PARSER *st); + +const char *my_xml_error_string(MY_XML_PARSER *st); + +#ifdef __cplusplus +} +#endif + +#endif /* _my_xml_h */ diff --git a/mysql_incl/myisampack.h b/mysql_incl/myisampack.h new file mode 100644 index 0000000..34a085e --- /dev/null +++ b/mysql_incl/myisampack.h @@ -0,0 +1,238 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Storing of values in high byte first order. + + integer keys and file pointers are stored with high byte first to get + better compression +*/ + +/* these two are for uniformity */ +#define mi_sint1korr(A) ((int8)(*A)) +#define mi_uint1korr(A) ((uint8)(*A)) + +#define mi_sint2korr(A) ((int16) (((int16) (((const uchar*) (A))[1])) +\ + ((int16) ((int16) ((const char*) (A))[0]) << 8))) +#define mi_sint3korr(A) ((int32) (((((const uchar*) (A))[0]) & 128) ? \ + (((uint32) 255L << 24) | \ + (((uint32) ((const uchar*) (A))[0]) << 16) |\ + (((uint32) ((const uchar*) (A))[1]) << 8) | \ + ((uint32) ((const uchar*) (A))[2])) : \ + (((uint32) ((const uchar*) (A))[0]) << 16) |\ + (((uint32) ((const uchar*) (A))[1]) << 8) | \ + ((uint32) ((const uchar*) (A))[2]))) +#define mi_sint4korr(A) ((int32) (((int32) (((const uchar*) (A))[3])) +\ + ((int32) (((const uchar*) (A))[2]) << 8) +\ + ((int32) (((const uchar*) (A))[1]) << 16) +\ + ((int32) ((int16) ((const char*) (A))[0]) << 24))) +#define mi_sint8korr(A) ((longlong) mi_uint8korr(A)) +#define mi_uint2korr(A) ((uint16) (((uint16) (((const uchar*) (A))[1])) +\ + ((uint16) (((const uchar*) (A))[0]) << 8))) +#define mi_uint3korr(A) ((uint32) (((uint32) (((const uchar*) (A))[2])) +\ + (((uint32) (((const uchar*) (A))[1])) << 8) +\ + (((uint32) (((const uchar*) (A))[0])) << 16))) +#define mi_uint4korr(A) ((uint32) (((uint32) (((const uchar*) (A))[3])) +\ + (((uint32) (((const uchar*) (A))[2])) << 8) +\ + (((uint32) (((const uchar*) (A))[1])) << 16) +\ + (((uint32) (((const uchar*) (A))[0])) << 24))) +#define mi_uint5korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[4])) +\ + (((uint32) (((const uchar*) (A))[3])) << 8) +\ + (((uint32) (((const uchar*) (A))[2])) << 16) +\ + (((uint32) (((const uchar*) (A))[1])) << 24)) +\ + (((ulonglong) (((const uchar*) (A))[0])) << 32)) +#define mi_uint6korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[5])) +\ + (((uint32) (((const uchar*) (A))[4])) << 8) +\ + (((uint32) (((const uchar*) (A))[3])) << 16) +\ + (((uint32) (((const uchar*) (A))[2])) << 24)) +\ + (((ulonglong) (((uint32) (((const uchar*) (A))[1])) +\ + (((uint32) (((const uchar*) (A))[0]) << 8)))) <<\ + 32)) +#define mi_uint7korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[6])) +\ + (((uint32) (((const uchar*) (A))[5])) << 8) +\ + (((uint32) (((const uchar*) (A))[4])) << 16) +\ + (((uint32) (((const uchar*) (A))[3])) << 24)) +\ + (((ulonglong) (((uint32) (((const uchar*) (A))[2])) +\ + (((uint32) (((const uchar*) (A))[1])) << 8) +\ + (((uint32) (((const uchar*) (A))[0])) << 16))) <<\ + 32)) +#define mi_uint8korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[7])) +\ + (((uint32) (((const uchar*) (A))[6])) << 8) +\ + (((uint32) (((const uchar*) (A))[5])) << 16) +\ + (((uint32) (((const uchar*) (A))[4])) << 24)) +\ + (((ulonglong) (((uint32) (((const uchar*) (A))[3])) +\ + (((uint32) (((const uchar*) (A))[2])) << 8) +\ + (((uint32) (((const uchar*) (A))[1])) << 16) +\ + (((uint32) (((const uchar*) (A))[0])) << 24))) <<\ + 32)) + +/* This one is for uniformity */ +#define mi_int1store(T,A) *((uchar*)(T))= (uchar) (A) + +#define mi_int2store(T,A) { uint def_temp= (uint) (A) ;\ + ((uchar*) (T))[1]= (uchar) (def_temp);\ + ((uchar*) (T))[0]= (uchar) (def_temp >> 8); } +#define mi_int3store(T,A) { /*lint -save -e734 */\ + ulong def_temp= (ulong) (A);\ + ((uchar*) (T))[2]= (uchar) (def_temp);\ + ((uchar*) (T))[1]= (uchar) (def_temp >> 8);\ + ((uchar*) (T))[0]= (uchar) (def_temp >> 16);\ + /*lint -restore */} +#define mi_int4store(T,A) { ulong def_temp= (ulong) (A);\ + ((uchar*) (T))[3]= (uchar) (def_temp);\ + ((uchar*) (T))[2]= (uchar) (def_temp >> 8);\ + ((uchar*) (T))[1]= (uchar) (def_temp >> 16);\ + ((uchar*) (T))[0]= (uchar) (def_temp >> 24); } +#define mi_int5store(T,A) { ulong def_temp= (ulong) (A),\ + def_temp2= (ulong) ((A) >> 32);\ + ((uchar*) (T))[4]= (uchar) (def_temp);\ + ((uchar*) (T))[3]= (uchar) (def_temp >> 8);\ + ((uchar*) (T))[2]= (uchar) (def_temp >> 16);\ + ((uchar*) (T))[1]= (uchar) (def_temp >> 24);\ + ((uchar*) (T))[0]= (uchar) (def_temp2); } +#define mi_int6store(T,A) { ulong def_temp= (ulong) (A),\ + def_temp2= (ulong) ((A) >> 32);\ + ((uchar*) (T))[5]= (uchar) (def_temp);\ + ((uchar*) (T))[4]= (uchar) (def_temp >> 8);\ + ((uchar*) (T))[3]= (uchar) (def_temp >> 16);\ + ((uchar*) (T))[2]= (uchar) (def_temp >> 24);\ + ((uchar*) (T))[1]= (uchar) (def_temp2);\ + ((uchar*) (T))[0]= (uchar) (def_temp2 >> 8); } +#define mi_int7store(T,A) { ulong def_temp= (ulong) (A),\ + def_temp2= (ulong) ((A) >> 32);\ + ((uchar*) (T))[6]= (uchar) (def_temp);\ + ((uchar*) (T))[5]= (uchar) (def_temp >> 8);\ + ((uchar*) (T))[4]= (uchar) (def_temp >> 16);\ + ((uchar*) (T))[3]= (uchar) (def_temp >> 24);\ + ((uchar*) (T))[2]= (uchar) (def_temp2);\ + ((uchar*) (T))[1]= (uchar) (def_temp2 >> 8);\ + ((uchar*) (T))[0]= (uchar) (def_temp2 >> 16); } +#define mi_int8store(T,A) { ulong def_temp3= (ulong) (A),\ + def_temp4= (ulong) ((A) >> 32);\ + mi_int4store((uchar*) (T) + 0, def_temp4);\ + mi_int4store((uchar*) (T) + 4, def_temp3); } + +#ifdef WORDS_BIGENDIAN + +#define mi_float4store(T,A) { ((uchar*) (T))[0]= ((uchar*) &A)[0];\ + ((uchar*) (T))[1]= ((uchar*) &A)[1];\ + ((uchar*) (T))[2]= ((uchar*) &A)[2];\ + ((uchar*) (T))[3]= ((uchar*) &A)[3]; } + +#define mi_float4get(V,M) { float def_temp;\ + ((uchar*) &def_temp)[0]= ((const uchar*) (M))[0];\ + ((uchar*) &def_temp)[1]= ((const uchar*) (M))[1]; \ + ((uchar*) &def_temp)[2]= ((const uchar*) (M))[2];\ + ((uchar*) &def_temp)[3]= ((const uchar*) (M))[3];\ + (V)= def_temp; } + +#define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[0];\ + ((uchar*) (T))[1]= ((const uchar*) &V)[1];\ + ((uchar*) (T))[2]= ((const uchar*) &V)[2];\ + ((uchar*) (T))[3]= ((const uchar*) &V)[3];\ + ((uchar*) (T))[4]= ((const uchar*) &V)[4];\ + ((uchar*) (T))[5]= ((const uchar*) &V)[5];\ + ((uchar*) (T))[6]= ((const uchar*) &V)[6];\ + ((uchar*) (T))[7]= ((const uchar*) &V)[7]; } + +#define mi_float8get(V,M) { double def_temp;\ + ((uchar*) &def_temp)[0]= ((const uchar*) (M))[0];\ + ((uchar*) &def_temp)[1]= ((const uchar*) (M))[1];\ + ((uchar*) &def_temp)[2]= ((const uchar*) (M))[2];\ + ((uchar*) &def_temp)[3]= ((const uchar*) (M))[3];\ + ((uchar*) &def_temp)[4]= ((const uchar*) (M))[4];\ + ((uchar*) &def_temp)[5]= ((const uchar*) (M))[5];\ + ((uchar*) &def_temp)[6]= ((const uchar*) (M))[6];\ + ((uchar*) &def_temp)[7]= ((const uchar*) (M))[7]; \ + (V)= def_temp; } +#else + +#define mi_float4store(T,A) { ((uchar*) (T))[0]= ((const uchar*) &A)[3];\ + ((uchar*) (T))[1]= ((const uchar*) &A)[2];\ + ((uchar*) (T))[2]= ((const uchar*) &A)[1];\ + ((uchar*) (T))[3]= ((const uchar*) &A)[0]; } + +#define mi_float4get(V,M) { float def_temp;\ + ((uchar*) &def_temp)[0]= ((const uchar*) (M))[3];\ + ((uchar*) &def_temp)[1]= ((const uchar*) (M))[2];\ + ((uchar*) &def_temp)[2]= ((const uchar*) (M))[1];\ + ((uchar*) &def_temp)[3]= ((const uchar*) (M))[0];\ + (V)= def_temp; } + +#if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) +#define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[3];\ + ((uchar*) (T))[1]= ((const uchar*) &V)[2];\ + ((uchar*) (T))[2]= ((const uchar*) &V)[1];\ + ((uchar*) (T))[3]= ((const uchar*) &V)[0];\ + ((uchar*) (T))[4]= ((const uchar*) &V)[7];\ + ((uchar*) (T))[5]= ((const uchar*) &V)[6];\ + ((uchar*) (T))[6]= ((const uchar*) &V)[5];\ + ((uchar*) (T))[7]= ((const uchar*) &V)[4];} + +#define mi_float8get(V,M) { double def_temp;\ + ((uchar*) &def_temp)[0]= ((const uchar*) (M))[3];\ + ((uchar*) &def_temp)[1]= ((const uchar*) (M))[2];\ + ((uchar*) &def_temp)[2]= ((const uchar*) (M))[1];\ + ((uchar*) &def_temp)[3]= ((const uchar*) (M))[0];\ + ((uchar*) &def_temp)[4]= ((const uchar*) (M))[7];\ + ((uchar*) &def_temp)[5]= ((const uchar*) (M))[6];\ + ((uchar*) &def_temp)[6]= ((const uchar*) (M))[5];\ + ((uchar*) &def_temp)[7]= ((const uchar*) (M))[4];\ + (V)= def_temp; } + +#else +#define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[7];\ + ((uchar*) (T))[1]= ((const uchar*) &V)[6];\ + ((uchar*) (T))[2]= ((const uchar*) &V)[5];\ + ((uchar*) (T))[3]= ((const uchar*) &V)[4];\ + ((uchar*) (T))[4]= ((const uchar*) &V)[3];\ + ((uchar*) (T))[5]= ((const uchar*) &V)[2];\ + ((uchar*) (T))[6]= ((const uchar*) &V)[1];\ + ((uchar*) (T))[7]= ((const uchar*) &V)[0];} + +#define mi_float8get(V,M) { double def_temp;\ + ((uchar*) &def_temp)[0]= ((const uchar*) (M))[7];\ + ((uchar*) &def_temp)[1]= ((const uchar*) (M))[6];\ + ((uchar*) &def_temp)[2]= ((const uchar*) (M))[5];\ + ((uchar*) &def_temp)[3]= ((const uchar*) (M))[4];\ + ((uchar*) &def_temp)[4]= ((const uchar*) (M))[3];\ + ((uchar*) &def_temp)[5]= ((const uchar*) (M))[2];\ + ((uchar*) &def_temp)[6]= ((const uchar*) (M))[1];\ + ((uchar*) &def_temp)[7]= ((const uchar*) (M))[0];\ + (V)= def_temp; } +#endif /* __FLOAT_WORD_ORDER */ +#endif /* WORDS_BIGENDIAN */ + +/* Fix to avoid warnings when sizeof(ha_rows) == sizeof(long) */ + +#ifdef BIG_TABLES +#define mi_rowstore(T,A) mi_int8store(T, A) +#define mi_rowkorr(T) mi_uint8korr(T) +#else +#define mi_rowstore(T,A) { mi_int4store(T, 0);\ + mi_int4store(((uchar*) (T) + 4), A); } +#define mi_rowkorr(T) mi_uint4korr((const uchar*) (T) + 4) +#endif + +#if SIZEOF_OFF_T > 4 +#define mi_sizestore(T,A) mi_int8store(T, A) +#define mi_sizekorr(T) mi_uint8korr(T) +#else +#define mi_sizestore(T,A) { if ((A) == HA_OFFSET_ERROR)\ + bfill((char*) (T), 8, 255);\ + else { mi_int4store((T), 0);\ + mi_int4store(((T) + 4), A); }} +#define mi_sizekorr(T) mi_uint4korr((const uchar*) (T) + 4) +#endif diff --git a/mysql_incl/mysql.h b/mysql_incl/mysql.h new file mode 100644 index 0000000..88333c4 --- /dev/null +++ b/mysql_incl/mysql.h @@ -0,0 +1,755 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + This file defines the client API to MySQL and also the ABI of the + dynamically linked libmysqlclient. + + The ABI should never be changed in a released product of MySQL + thus you need to take great care when changing the file. In case + the file is changed so the ABI is broken, you must also + update the SHAREDLIB_MAJOR_VERSION in configure.in . + +*/ + +#ifndef _mysql_h +#define _mysql_h + +#ifdef _AIX /* large-file support will break without this */ +#include +#endif + +#ifdef __CYGWIN__ /* CYGWIN implements a UNIX API */ +#undef WIN +#undef _WIN +#undef _WIN32 +#undef _WIN64 +#undef __WIN__ +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _global_h /* If not standard header */ +#include +#ifdef __LCC__ +#include /* For windows */ +#endif +typedef char my_bool; +#if (defined(_WIN32) || defined(_WIN64)) && !defined(__WIN__) +#define __WIN__ +#endif +#if !defined(__WIN__) +#define STDCALL +#else +#define STDCALL __stdcall +#endif + +#ifndef my_socket_defined +#ifdef __WIN__ +#define my_socket SOCKET +#else +typedef int my_socket; +#endif /* __WIN__ */ +#endif /* my_socket_defined */ +#endif /* _global_h */ + +#include "mysql_version.h" +#include "mysql_com.h" +#include "mysql_time.h" + +#include "my_list.h" /* for LISTs used in 'MYSQL' and 'MYSQL_STMT' */ + +extern unsigned int mysql_port; +extern char *mysql_unix_port; + +#define CLIENT_NET_READ_TIMEOUT 365*24*3600 /* Timeout on read */ +#define CLIENT_NET_WRITE_TIMEOUT 365*24*3600 /* Timeout on write */ + +#ifdef __NETWARE__ +#pragma pack(push, 8) /* 8 byte alignment */ +#endif + +#define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG) +#define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG) +#define IS_BLOB(n) ((n) & BLOB_FLAG) +#define IS_NUM(t) ((t) <= MYSQL_TYPE_INT24 || (t) == MYSQL_TYPE_YEAR || (t) == MYSQL_TYPE_NEWDECIMAL) +#define IS_NUM_FIELD(f) ((f)->flags & NUM_FLAG) +#define INTERNAL_NUM_FIELD(f) (((f)->type <= MYSQL_TYPE_INT24 && ((f)->type != MYSQL_TYPE_TIMESTAMP || (f)->length == 14 || (f)->length == 8)) || (f)->type == MYSQL_TYPE_YEAR) +#define IS_LONGDATA(t) ((t) >= MYSQL_TYPE_TINY_BLOB && (t) <= MYSQL_TYPE_STRING) + + +typedef struct st_mysql_field { + char *name; /* Name of column */ + char *org_name; /* Original column name, if an alias */ + char *table; /* Table of column if column was a field */ + char *org_table; /* Org table name, if table was an alias */ + char *db; /* Database for table */ + char *catalog; /* Catalog for table */ + char *def; /* Default value (set by mysql_list_fields) */ + unsigned long length; /* Width of column (create length) */ + unsigned long max_length; /* Max width for selected set */ + unsigned int name_length; + unsigned int org_name_length; + unsigned int table_length; + unsigned int org_table_length; + unsigned int db_length; + unsigned int catalog_length; + unsigned int def_length; + unsigned int flags; /* Div flags */ + unsigned int decimals; /* Number of decimals in field */ + unsigned int charsetnr; /* Character set */ + enum enum_field_types type; /* Type of field. See mysql_com.h for types */ + void *extension; +} MYSQL_FIELD; + +typedef char **MYSQL_ROW; /* return data as array of strings */ +typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */ + +#ifndef _global_h +#if defined(NO_CLIENT_LONG_LONG) +typedef unsigned long my_ulonglong; +#elif defined (__WIN__) +typedef unsigned __int64 my_ulonglong; +#else +typedef unsigned long long my_ulonglong; +#endif +#endif + +#include "typelib.h" + +#define MYSQL_COUNT_ERROR (~(my_ulonglong) 0) + +/* backward compatibility define - to be removed eventually */ +#define ER_WARN_DATA_TRUNCATED WARN_DATA_TRUNCATED + +typedef struct st_mysql_rows { + struct st_mysql_rows *next; /* list of rows */ + MYSQL_ROW data; + unsigned long length; +} MYSQL_ROWS; + +typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */ + +#include "my_alloc.h" + +typedef struct embedded_query_result EMBEDDED_QUERY_RESULT; +typedef struct st_mysql_data { + MYSQL_ROWS *data; + struct embedded_query_result *embedded_info; + MEM_ROOT alloc; + my_ulonglong rows; + unsigned int fields; + /* extra info for embedded library */ + void *extension; +} MYSQL_DATA; + +enum mysql_option +{ + MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE, + MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP, + MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE, + MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT, + MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT, + MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION, + MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH, + MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT, + MYSQL_OPT_SSL_VERIFY_SERVER_CERT +}; + +struct st_mysql_options { + unsigned int connect_timeout, read_timeout, write_timeout; + unsigned int port, protocol; + unsigned long client_flag; + char *host,*user,*password,*unix_socket,*db; + struct st_dynamic_array *init_commands; + char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name; + char *ssl_key; /* PEM key file */ + char *ssl_cert; /* PEM cert file */ + char *ssl_ca; /* PEM CA file */ + char *ssl_capath; /* PEM directory of CA-s? */ + char *ssl_cipher; /* cipher to use */ + char *shared_memory_base_name; + unsigned long max_allowed_packet; + my_bool use_ssl; /* if to use SSL or not */ + my_bool compress,named_pipe; + my_bool unused1; + my_bool unused2; + my_bool unused3; + my_bool unused4; + enum mysql_option methods_to_use; + char *client_ip; + /* Refuse client connecting to server if it uses old (pre-4.1.1) protocol */ + my_bool secure_auth; + /* 0 - never report, 1 - always report (default) */ + my_bool report_data_truncation; + + /* function pointers for local infile support */ + int (*local_infile_init)(void **, const char *, void *); + int (*local_infile_read)(void *, char *, unsigned int); + void (*local_infile_end)(void *); + int (*local_infile_error)(void *, char *, unsigned int); + void *local_infile_userdata; + void *extension; +}; + +enum mysql_status +{ + MYSQL_STATUS_READY,MYSQL_STATUS_GET_RESULT,MYSQL_STATUS_USE_RESULT +}; + +enum mysql_protocol_type +{ + MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET, + MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY +}; + +typedef struct character_set +{ + unsigned int number; /* character set number */ + unsigned int state; /* character set state */ + const char *csname; /* collation name */ + const char *name; /* character set name */ + const char *comment; /* comment */ + const char *dir; /* character set directory */ + unsigned int mbminlen; /* min. length for multibyte strings */ + unsigned int mbmaxlen; /* max. length for multibyte strings */ +} MY_CHARSET_INFO; + +struct st_mysql_methods; +struct st_mysql_stmt; + +typedef struct st_mysql +{ + NET net; /* Communication parameters */ + unsigned char *connector_fd; /* ConnectorFd for SSL */ + char *host,*user,*passwd,*unix_socket,*server_version,*host_info; + char *info, *db; + struct charset_info_st *charset; + MYSQL_FIELD *fields; + MEM_ROOT field_alloc; + my_ulonglong affected_rows; + my_ulonglong insert_id; /* id if insert on table with NEXTNR */ + my_ulonglong extra_info; /* Not used */ + unsigned long thread_id; /* Id for connection in server */ + unsigned long packet_length; + unsigned int port; + unsigned long client_flag,server_capabilities; + unsigned int protocol_version; + unsigned int field_count; + unsigned int server_status; + unsigned int server_language; + unsigned int warning_count; + struct st_mysql_options options; + enum mysql_status status; + my_bool free_me; /* If free in mysql_close */ + my_bool reconnect; /* set to 1 if automatic reconnect */ + + /* session-wide random string */ + char scramble[SCRAMBLE_LENGTH+1]; + my_bool unused1; + void *unused2, *unused3, *unused4, *unused5; + + LIST *stmts; /* list of all statements */ + const struct st_mysql_methods *methods; + void *thd; + /* + Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag + from mysql_stmt_close if close had to cancel result set of this object. + */ + my_bool *unbuffered_fetch_owner; + /* needed for embedded server - no net buffer to store the 'info' */ + char *info_buffer; + void *extension; +} MYSQL; + + +typedef struct st_mysql_res { + my_ulonglong row_count; + MYSQL_FIELD *fields; + MYSQL_DATA *data; + MYSQL_ROWS *data_cursor; + unsigned long *lengths; /* column lengths of current row */ + MYSQL *handle; /* for unbuffered reads */ + const struct st_mysql_methods *methods; + MYSQL_ROW row; /* If unbuffered read */ + MYSQL_ROW current_row; /* buffer to current row */ + MEM_ROOT field_alloc; + unsigned int field_count, current_field; + my_bool eof; /* Used by mysql_fetch_row */ + /* mysql_stmt_close() had to cancel this result */ + my_bool unbuffered_fetch_cancelled; + void *extension; +} MYSQL_RES; + + +#if !defined(MYSQL_SERVER) && !defined(MYSQL_CLIENT) +#define MYSQL_CLIENT +#endif + + +typedef struct st_mysql_parameters +{ + unsigned long *p_max_allowed_packet; + unsigned long *p_net_buffer_length; + void *extension; +} MYSQL_PARAMETERS; + +#if !defined(MYSQL_SERVER) && !defined(EMBEDDED_LIBRARY) +#define max_allowed_packet (*mysql_get_parameters()->p_max_allowed_packet) +#define net_buffer_length (*mysql_get_parameters()->p_net_buffer_length) +#endif + +/* + Set up and bring down the server; to ensure that applications will + work when linked against either the standard client library or the + embedded server library, these functions should be called. +*/ +int STDCALL mysql_server_init(int argc, char **argv, char **groups); +void STDCALL mysql_server_end(void); + +/* + mysql_server_init/end need to be called when using libmysqld or + libmysqlclient (exactly, mysql_server_init() is called by mysql_init() so + you don't need to call it explicitely; but you need to call + mysql_server_end() to free memory). The names are a bit misleading + (mysql_SERVER* to be used when using libmysqlCLIENT). So we add more general + names which suit well whether you're using libmysqld or libmysqlclient. We + intend to promote these aliases over the mysql_server* ones. +*/ +#define mysql_library_init mysql_server_init +#define mysql_library_end mysql_server_end + +MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void); + +/* + Set up and bring down a thread; these function should be called + for each thread in an application which opens at least one MySQL + connection. All uses of the connection(s) should be between these + function calls. +*/ +my_bool STDCALL mysql_thread_init(void); +void STDCALL mysql_thread_end(void); + +/* + Functions to get information from the MYSQL and MYSQL_RES structures + Should definitely be used if one uses shared libraries. +*/ + +my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res); +unsigned int STDCALL mysql_num_fields(MYSQL_RES *res); +my_bool STDCALL mysql_eof(MYSQL_RES *res); +MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res, + unsigned int fieldnr); +MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res); +MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res); +MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res); + +unsigned int STDCALL mysql_field_count(MYSQL *mysql); +my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql); +my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql); +unsigned int STDCALL mysql_errno(MYSQL *mysql); +const char * STDCALL mysql_error(MYSQL *mysql); +const char *STDCALL mysql_sqlstate(MYSQL *mysql); +unsigned int STDCALL mysql_warning_count(MYSQL *mysql); +const char * STDCALL mysql_info(MYSQL *mysql); +unsigned long STDCALL mysql_thread_id(MYSQL *mysql); +const char * STDCALL mysql_character_set_name(MYSQL *mysql); +int STDCALL mysql_set_character_set(MYSQL *mysql, const char *csname); + +MYSQL * STDCALL mysql_init(MYSQL *mysql); +my_bool STDCALL mysql_ssl_set(MYSQL *mysql, const char *key, + const char *cert, const char *ca, + const char *capath, const char *cipher); +const char * STDCALL mysql_get_ssl_cipher(MYSQL *mysql); +my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user, + const char *passwd, const char *db); +MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host, + const char *user, + const char *passwd, + const char *db, + unsigned int port, + const char *unix_socket, + unsigned long clientflag); +int STDCALL mysql_select_db(MYSQL *mysql, const char *db); +int STDCALL mysql_query(MYSQL *mysql, const char *q); +int STDCALL mysql_send_query(MYSQL *mysql, const char *q, + unsigned long length); +int STDCALL mysql_real_query(MYSQL *mysql, const char *q, + unsigned long length); +MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql); +MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql); + +void STDCALL mysql_get_character_set_info(MYSQL *mysql, + MY_CHARSET_INFO *charset); + +/* local infile support */ + +#define LOCAL_INFILE_ERROR_LEN 512 + +void +mysql_set_local_infile_handler(MYSQL *mysql, + int (*local_infile_init)(void **, const char *, + void *), + int (*local_infile_read)(void *, char *, + unsigned int), + void (*local_infile_end)(void *), + int (*local_infile_error)(void *, char*, + unsigned int), + void *); + +void +mysql_set_local_infile_default(MYSQL *mysql); + +int STDCALL mysql_shutdown(MYSQL *mysql, + enum mysql_enum_shutdown_level + shutdown_level); +int STDCALL mysql_dump_debug_info(MYSQL *mysql); +int STDCALL mysql_refresh(MYSQL *mysql, + unsigned int refresh_options); +int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid); +int STDCALL mysql_set_server_option(MYSQL *mysql, + enum enum_mysql_set_option + option); +int STDCALL mysql_ping(MYSQL *mysql); +const char * STDCALL mysql_stat(MYSQL *mysql); +const char * STDCALL mysql_get_server_info(MYSQL *mysql); +const char * STDCALL mysql_get_client_info(void); +unsigned long STDCALL mysql_get_client_version(void); +const char * STDCALL mysql_get_host_info(MYSQL *mysql); +unsigned long STDCALL mysql_get_server_version(MYSQL *mysql); +unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql); +MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild); +MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild); +MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql); +int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option, + const void *arg); +void STDCALL mysql_free_result(MYSQL_RES *result); +void STDCALL mysql_data_seek(MYSQL_RES *result, + my_ulonglong offset); +MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result, + MYSQL_ROW_OFFSET offset); +MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result, + MYSQL_FIELD_OFFSET offset); +MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); +unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result); +MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result); +MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table, + const char *wild); +unsigned long STDCALL mysql_escape_string(char *to,const char *from, + unsigned long from_length); +unsigned long STDCALL mysql_hex_string(char *to,const char *from, + unsigned long from_length); +unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql, + char *to,const char *from, + unsigned long length); +void STDCALL mysql_debug(const char *debug); +void STDCALL myodbc_remove_escape(MYSQL *mysql,char *name); +unsigned int STDCALL mysql_thread_safe(void); +my_bool STDCALL mysql_embedded(void); +my_bool STDCALL mysql_read_query_result(MYSQL *mysql); + + +/* + The following definitions are added for the enhanced + client-server protocol +*/ + +/* statement state */ +enum enum_mysql_stmt_state +{ + MYSQL_STMT_INIT_DONE= 1, MYSQL_STMT_PREPARE_DONE, MYSQL_STMT_EXECUTE_DONE, + MYSQL_STMT_FETCH_DONE +}; + + +/* + This structure is used to define bind information, and + internally by the client library. + Public members with their descriptions are listed below + (conventionally `On input' refers to the binds given to + mysql_stmt_bind_param, `On output' refers to the binds given + to mysql_stmt_bind_result): + + buffer_type - One of the MYSQL_* types, used to describe + the host language type of buffer. + On output: if column type is different from + buffer_type, column value is automatically converted + to buffer_type before it is stored in the buffer. + buffer - On input: points to the buffer with input data. + On output: points to the buffer capable to store + output data. + The type of memory pointed by buffer must correspond + to buffer_type. See the correspondence table in + the comment to mysql_stmt_bind_param. + + The two above members are mandatory for any kind of bind. + + buffer_length - the length of the buffer. You don't have to set + it for any fixed length buffer: float, double, + int, etc. It must be set however for variable-length + types, such as BLOBs or STRINGs. + + length - On input: in case when lengths of input values + are different for each execute, you can set this to + point at a variable containining value length. This + way the value length can be different in each execute. + If length is not NULL, buffer_length is not used. + Note, length can even point at buffer_length if + you keep bind structures around while fetching: + this way you can change buffer_length before + each execution, everything will work ok. + On output: if length is set, mysql_stmt_fetch will + write column length into it. + + is_null - On input: points to a boolean variable that should + be set to TRUE for NULL values. + This member is useful only if your data may be + NULL in some but not all cases. + If your data is never NULL, is_null should be set to 0. + If your data is always NULL, set buffer_type + to MYSQL_TYPE_NULL, and is_null will not be used. + + is_unsigned - On input: used to signify that values provided for one + of numeric types are unsigned. + On output describes signedness of the output buffer. + If, taking into account is_unsigned flag, column data + is out of range of the output buffer, data for this column + is regarded truncated. Note that this has no correspondence + to the sign of result set column, if you need to find it out + use mysql_stmt_result_metadata. + error - where to write a truncation error if it is present. + possible error value is: + 0 no truncation + 1 value is out of range or buffer is too small + + Please note that MYSQL_BIND also has internals members. +*/ + +typedef struct st_mysql_bind +{ + unsigned long *length; /* output length pointer */ + my_bool *is_null; /* Pointer to null indicator */ + void *buffer; /* buffer to get/put data */ + /* set this if you want to track data truncations happened during fetch */ + my_bool *error; + unsigned char *row_ptr; /* for the current data position */ + void (*store_param_func)(NET *net, struct st_mysql_bind *param); + void (*fetch_result)(struct st_mysql_bind *, MYSQL_FIELD *, + unsigned char **row); + void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *, + unsigned char **row); + /* output buffer length, must be set when fetching str/binary */ + unsigned long buffer_length; + unsigned long offset; /* offset position for char/binary fetch */ + unsigned long length_value; /* Used if length is 0 */ + unsigned int param_number; /* For null count and error messages */ + unsigned int pack_length; /* Internal length for packed data */ + enum enum_field_types buffer_type; /* buffer type */ + my_bool error_value; /* used if error is 0 */ + my_bool is_unsigned; /* set if integer type is unsigned */ + my_bool long_data_used; /* If used with mysql_send_long_data */ + my_bool is_null_value; /* Used if is_null is 0 */ + void *extension; +} MYSQL_BIND; + + +/* statement handler */ +typedef struct st_mysql_stmt +{ + MEM_ROOT mem_root; /* root allocations */ + LIST list; /* list to keep track of all stmts */ + MYSQL *mysql; /* connection handle */ + MYSQL_BIND *params; /* input parameters */ + MYSQL_BIND *bind; /* output parameters */ + MYSQL_FIELD *fields; /* result set metadata */ + MYSQL_DATA result; /* cached result set */ + MYSQL_ROWS *data_cursor; /* current row in cached result */ + /* + mysql_stmt_fetch() calls this function to fetch one row (it's different + for buffered, unbuffered and cursor fetch). + */ + int (*read_row_func)(struct st_mysql_stmt *stmt, + unsigned char **row); + /* copy of mysql->affected_rows after statement execution */ + my_ulonglong affected_rows; + my_ulonglong insert_id; /* copy of mysql->insert_id */ + unsigned long stmt_id; /* Id for prepared statement */ + unsigned long flags; /* i.e. type of cursor to open */ + unsigned long prefetch_rows; /* number of rows per one COM_FETCH */ + /* + Copied from mysql->server_status after execute/fetch to know + server-side cursor status for this statement. + */ + unsigned int server_status; + unsigned int last_errno; /* error code */ + unsigned int param_count; /* input parameter count */ + unsigned int field_count; /* number of columns in result set */ + enum enum_mysql_stmt_state state; /* statement state */ + char last_error[MYSQL_ERRMSG_SIZE]; /* error message */ + char sqlstate[SQLSTATE_LENGTH+1]; + /* Types of input parameters should be sent to server */ + my_bool send_types_to_server; + my_bool bind_param_done; /* input buffers were supplied */ + unsigned char bind_result_done; /* output buffers were supplied */ + /* mysql_stmt_close() had to cancel this result */ + my_bool unbuffered_fetch_cancelled; + /* + Is set to true if we need to calculate field->max_length for + metadata fields when doing mysql_stmt_store_result. + */ + my_bool update_max_length; + void *extension; +} MYSQL_STMT; + +enum enum_stmt_attr_type +{ + /* + When doing mysql_stmt_store_result calculate max_length attribute + of statement metadata. This is to be consistent with the old API, + where this was done automatically. + In the new API we do that only by request because it slows down + mysql_stmt_store_result sufficiently. + */ + STMT_ATTR_UPDATE_MAX_LENGTH, + /* + unsigned long with combination of cursor flags (read only, for update, + etc) + */ + STMT_ATTR_CURSOR_TYPE, + /* + Amount of rows to retrieve from server per one fetch if using cursors. + Accepts unsigned long attribute in the range 1 - ulong_max + */ + STMT_ATTR_PREFETCH_ROWS +}; + + +typedef struct st_mysql_methods +{ + my_bool (*read_query_result)(MYSQL *mysql); + my_bool (*advanced_command)(MYSQL *mysql, + enum enum_server_command command, + const unsigned char *header, + unsigned long header_length, + const unsigned char *arg, + unsigned long arg_length, + my_bool skip_check, + MYSQL_STMT *stmt); + MYSQL_DATA *(*read_rows)(MYSQL *mysql,MYSQL_FIELD *mysql_fields, + unsigned int fields); + MYSQL_RES * (*use_result)(MYSQL *mysql); + void (*fetch_lengths)(unsigned long *to, + MYSQL_ROW column, unsigned int field_count); + void (*flush_use_result)(MYSQL *mysql, my_bool flush_all_results); +#if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) + MYSQL_FIELD * (*list_fields)(MYSQL *mysql); + my_bool (*read_prepare_result)(MYSQL *mysql, MYSQL_STMT *stmt); + int (*stmt_execute)(MYSQL_STMT *stmt); + int (*read_binary_rows)(MYSQL_STMT *stmt); + int (*unbuffered_fetch)(MYSQL *mysql, char **row); + void (*free_embedded_thd)(MYSQL *mysql); + const char *(*read_statistics)(MYSQL *mysql); + my_bool (*next_result)(MYSQL *mysql); + int (*read_change_user_result)(MYSQL *mysql, char *buff, const char *passwd); + int (*read_rows_from_cursor)(MYSQL_STMT *stmt); +#endif +} MYSQL_METHODS; + + +MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql); +int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, + unsigned long length); +int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt); +int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt); +int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind_arg, + unsigned int column, + unsigned long offset); +int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt); +unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt); +my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt, + enum enum_stmt_attr_type attr_type, + const void *attr); +my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt, + enum enum_stmt_attr_type attr_type, + void *attr); +my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd); +my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd); +my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt); +my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt); +my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt); +my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt, + unsigned int param_number, + const char *data, + unsigned long length); +MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt); +MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt); +unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt); +const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt); +const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt); +MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt, + MYSQL_ROW_OFFSET offset); +MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt); +void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset); +my_ulonglong STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt); +my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt); +my_ulonglong STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt); +unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt); + +my_bool STDCALL mysql_commit(MYSQL * mysql); +my_bool STDCALL mysql_rollback(MYSQL * mysql); +my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode); +my_bool STDCALL mysql_more_results(MYSQL *mysql); +int STDCALL mysql_next_result(MYSQL *mysql); +int STDCALL mysql_stmt_next_result(MYSQL_STMT *stmt); +void STDCALL mysql_close(MYSQL *sock); + + +/* status return codes */ +#define MYSQL_NO_DATA 100 +#define MYSQL_DATA_TRUNCATED 101 + +#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT) + +#ifdef USE_OLD_FUNCTIONS +MYSQL * STDCALL mysql_connect(MYSQL *mysql, const char *host, + const char *user, const char *passwd); +int STDCALL mysql_create_db(MYSQL *mysql, const char *DB); +int STDCALL mysql_drop_db(MYSQL *mysql, const char *DB); +#endif +#define HAVE_MYSQL_REAL_CONNECT + +/* + The following functions are mainly exported because of mysqlbinlog; + They are not for general usage +*/ + +#define simple_command(mysql, command, arg, length, skip_check) \ + (*(mysql)->methods->advanced_command)(mysql, command, 0, \ + 0, arg, length, skip_check, NULL) +#define stmt_command(mysql, command, arg, length, stmt) \ + (*(mysql)->methods->advanced_command)(mysql, command, 0, \ + 0, arg, length, 1, stmt) + +#ifdef __NETWARE__ +#pragma pack(pop) /* restore alignment */ +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _mysql_h */ diff --git a/mysql_incl/mysql_com.h b/mysql_incl/mysql_com.h new file mode 100644 index 0000000..8b16fd2 --- /dev/null +++ b/mysql_incl/mysql_com.h @@ -0,0 +1,543 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* +** Common definition between mysql server & client +*/ + +#ifndef _mysql_com_h +#define _mysql_com_h + +#define HOSTNAME_LENGTH 60 +#define SYSTEM_CHARSET_MBMAXLEN 4 +#define NAME_CHAR_LEN 64 /* Field/table name length */ +#define USERNAME_CHAR_LENGTH 16 +#define NAME_LEN (NAME_CHAR_LEN*SYSTEM_CHARSET_MBMAXLEN) +#define USERNAME_LENGTH (USERNAME_CHAR_LENGTH*SYSTEM_CHARSET_MBMAXLEN) + +#define SERVER_VERSION_LENGTH 60 +#define SQLSTATE_LENGTH 5 + +/* + Maximum length of comments +*/ +#define TABLE_COMMENT_INLINE_MAXLEN 180 /* pre 6.0: 60 (3-byte) characters */ +#define TABLE_COMMENT_MAXLEN 2048 +#define COLUMN_COMMENT_MAXLEN 1024 +#define INDEX_COMMENT_MAXLEN 1024 + + +/* + USER_HOST_BUFF_SIZE -- length of string buffer, that is enough to contain + username and hostname parts of the user identifier with trailing zero in + MySQL standard format: + user_name_part@host_name_part\0 +*/ +#define USER_HOST_BUFF_SIZE HOSTNAME_LENGTH + USERNAME_LENGTH + 2 + +#define LOCAL_HOST "localhost" +#define LOCAL_HOST_NAMEDPIPE "." + + +#if defined(__WIN__) && !defined( _CUSTOMCONFIG_) +#define MYSQL_NAMEDPIPE "MySQL" +#define MYSQL_SERVICENAME "MySQL" +#endif /* __WIN__ */ + +/* + You should add new commands to the end of this list, otherwise old + servers won't be able to handle them as 'unsupported'. +*/ + +enum enum_server_command +{ + COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, + COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, + COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, + COM_TIME, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, + COM_TABLE_DUMP, COM_CONNECT_OUT, COM_REGISTER_SLAVE, + COM_STMT_PREPARE, COM_STMT_EXECUTE, COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, + COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH, COM_DAEMON, + /* don't forget to update const char *command_name[] in sql_parse.cc */ + + /* Must be last */ + COM_END +}; + + +/* + Length of random string sent by server on handshake; this is also length of + obfuscated password, recieved from client +*/ +#define SCRAMBLE_LENGTH 20 +#define SCRAMBLE_LENGTH_323 8 +/* length of password stored in the db: new passwords are preceeded with '*' */ +#define SCRAMBLED_PASSWORD_CHAR_LENGTH (SCRAMBLE_LENGTH*2+1) +#define SCRAMBLED_PASSWORD_CHAR_LENGTH_323 (SCRAMBLE_LENGTH_323*2) + + +#define NOT_NULL_FLAG 1 /* Field can't be NULL */ +#define PRI_KEY_FLAG 2 /* Field is part of a primary key */ +#define UNIQUE_KEY_FLAG 4 /* Field is part of a unique key */ +#define MULTIPLE_KEY_FLAG 8 /* Field is part of a key */ +#define BLOB_FLAG 16 /* Field is a blob */ +#define UNSIGNED_FLAG 32 /* Field is unsigned */ +#define ZEROFILL_FLAG 64 /* Field is zerofill */ +#define BINARY_FLAG 128 /* Field is binary */ + +/* The following are only sent to new clients */ +#define ENUM_FLAG 256 /* field is an enum */ +#define AUTO_INCREMENT_FLAG 512 /* field is a autoincrement field */ +#define TIMESTAMP_FLAG 1024 /* Field is a timestamp */ +#define SET_FLAG 2048 /* field is a set */ +#define NO_DEFAULT_VALUE_FLAG 4096 /* Field doesn't have default value */ +#define ON_UPDATE_NOW_FLAG 8192 /* Field is set to NOW on UPDATE */ +#define NUM_FLAG 32768 /* Field is num (for clients) */ +#define PART_KEY_FLAG 16384 /* Intern; Part of some key */ +#define GROUP_FLAG 32768 /* Intern: Group field */ +#define UNIQUE_FLAG 65536 /* Intern: Used by sql_yacc */ +#define BINCMP_FLAG 131072 /* Intern: Used by sql_yacc */ +#define GET_FIXED_FIELDS_FLAG (1 << 18) /* Used to get fields in item tree */ +#define FIELD_IN_PART_FUNC_FLAG (1 << 19)/* Field part of partition func */ +#define FIELD_IN_ADD_INDEX (1<< 20) /* Intern: Field used in ADD INDEX */ +#define FIELD_IS_RENAMED (1<< 21) /* Intern: Field is being renamed */ +#define FIELD_STORAGE_FLAGS 22 /* Storage type: bit 22, 23 and 24 */ +#define COLUMN_FORMAT_FLAGS 25 /* Column format: bit 25, 26 and 27 */ + +#define REFRESH_GRANT 1 /* Refresh grant tables */ +#define REFRESH_LOG 2 /* Start on new log file */ +#define REFRESH_TABLES 4 /* close all tables */ +#define REFRESH_HOSTS 8 /* Flush host cache */ +#define REFRESH_STATUS 16 /* Flush status variables */ +#define REFRESH_THREADS 32 /* Flush thread cache */ +#define REFRESH_SLAVE 64 /* Reset master info and restart slave + thread */ +#define REFRESH_MASTER 128 /* Remove all bin logs in the index + and truncate the index */ + +/* The following can't be set with mysql_refresh() */ +#define REFRESH_READ_LOCK 16384 /* Lock tables for read */ +#define REFRESH_FAST 32768 /* Intern flag */ + +/* RESET (remove all queries) from query cache */ +#define REFRESH_QUERY_CACHE 65536 +#define REFRESH_QUERY_CACHE_FREE 0x20000L /* pack query cache */ +#define REFRESH_DES_KEY_FILE 0x40000L +#define REFRESH_USER_RESOURCES 0x80000L +#define REFRESH_BACKUP_LOG 0x200000L + +#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */ +#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */ +#define CLIENT_LONG_FLAG 4 /* Get all column flags */ +#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */ +#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */ +#define CLIENT_COMPRESS 32 /* Can use compression protocol */ +#define CLIENT_ODBC 64 /* Odbc client */ +#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */ +#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */ +#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */ +#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */ +#define CLIENT_SSL 2048 /* Switch to SSL after handshake */ +#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */ +#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */ +#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */ +#define CLIENT_SECURE_CONNECTION 32768 /* New 4.1 authentication */ +#define CLIENT_MULTI_STATEMENTS (1UL << 16) /* Enable/disable multi-stmt support */ +#define CLIENT_MULTI_RESULTS (1UL << 17) /* Enable/disable multi-results */ +#define CLIENT_PS_MULTI_RESULTS (1UL << 18) /* Multi-results in PS-protocol */ + +#define CLIENT_SSL_VERIFY_SERVER_CERT (1UL << 30) +#define CLIENT_REMEMBER_OPTIONS (1UL << 31) + +/* Gather all possible capabilites (flags) supported by the server */ +#define CLIENT_ALL_FLAGS (CLIENT_LONG_PASSWORD | \ + CLIENT_FOUND_ROWS | \ + CLIENT_LONG_FLAG | \ + CLIENT_CONNECT_WITH_DB | \ + CLIENT_NO_SCHEMA | \ + CLIENT_COMPRESS | \ + CLIENT_ODBC | \ + CLIENT_LOCAL_FILES | \ + CLIENT_IGNORE_SPACE | \ + CLIENT_PROTOCOL_41 | \ + CLIENT_INTERACTIVE | \ + CLIENT_SSL | \ + CLIENT_IGNORE_SIGPIPE | \ + CLIENT_TRANSACTIONS | \ + CLIENT_RESERVED | \ + CLIENT_SECURE_CONNECTION | \ + CLIENT_MULTI_STATEMENTS | \ + CLIENT_MULTI_RESULTS | \ + CLIENT_PS_MULTI_RESULTS | \ + CLIENT_SSL_VERIFY_SERVER_CERT | \ + CLIENT_REMEMBER_OPTIONS) + +/* + Switch off the flags that are optional and depending on build flags + If any of the optional flags is supported by the build it will be switched + on before sending to the client during the connection handshake. +*/ +#define CLIENT_BASIC_FLAGS (((CLIENT_ALL_FLAGS & ~CLIENT_SSL) \ + & ~CLIENT_COMPRESS) \ + & ~CLIENT_SSL_VERIFY_SERVER_CERT) + +#define SERVER_STATUS_IN_TRANS 1 /* Transaction has started */ +#define SERVER_STATUS_AUTOCOMMIT 2 /* Server in auto_commit mode */ +#define SERVER_MORE_RESULTS_EXISTS 8 /* Multi query - next query exists */ +#define SERVER_QUERY_NO_GOOD_INDEX_USED 16 +#define SERVER_QUERY_NO_INDEX_USED 32 +/** + The server was able to fulfill the clients request and opened a + read-only non-scrollable cursor for a query. This flag comes + in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. +*/ +#define SERVER_STATUS_CURSOR_EXISTS 64 +/** + This flag is sent when a read-only cursor is exhausted, in reply to + COM_STMT_FETCH command. +*/ +#define SERVER_STATUS_LAST_ROW_SENT 128 +#define SERVER_STATUS_DB_DROPPED 256 /* A database was dropped */ +#define SERVER_STATUS_NO_BACKSLASH_ESCAPES 512 +/** + Sent to the client if after a prepared statement reprepare + we discovered that the new statement returns a different + number of result set columns. +*/ +#define SERVER_STATUS_METADATA_CHANGED 1024 +/* + Tell clients that this query was logged to the slow query log. + Not yet set in the server, but interface is defined for applications + to use. See WorkLog 4098. +*/ +#define SERVER_QUERY_WAS_SLOW 2048 + +/** + To mark ResultSet containing output parameter values. +*/ +#define SERVER_PS_OUT_PARAMS 4096 + +/** + Server status flags that must be cleared when starting + execution of a new SQL statement. + Flags from this set are only added to the + current server status by the execution engine, but + never removed -- the execution engine expects them + to disappear automagically by the next command. +*/ +#define SERVER_STATUS_CLEAR_SET (SERVER_QUERY_NO_GOOD_INDEX_USED| \ + SERVER_QUERY_NO_INDEX_USED|\ + SERVER_MORE_RESULTS_EXISTS|\ + SERVER_STATUS_METADATA_CHANGED) + +#define MYSQL_ERRMSG_SIZE 512 +#define NET_READ_TIMEOUT 30 /* Timeout on read */ +#define NET_WRITE_TIMEOUT 60 /* Timeout on write */ +#define NET_WAIT_TIMEOUT 8*60*60 /* Wait for new query */ + +#define ONLY_KILL_QUERY 1 + + +struct st_vio; /* Only C */ +typedef struct st_vio Vio; + +#define MAX_TINYINT_WIDTH 3 /* Max width for a TINY w.o. sign */ +#define MAX_SMALLINT_WIDTH 5 /* Max width for a SHORT w.o. sign */ +#define MAX_MEDIUMINT_WIDTH 8 /* Max width for a INT24 w.o. sign */ +#define MAX_INT_WIDTH 10 /* Max width for a LONG w.o. sign */ +#define MAX_BIGINT_WIDTH 20 /* Max width for a LONGLONG */ +#define MAX_CHAR_WIDTH 255 /* Max length for a CHAR colum */ +#define MAX_BLOB_WIDTH 16777216 /* Default width for blob */ + +typedef struct st_net { +#if !defined(CHECK_EMBEDDED_DIFFERENCES) || !defined(EMBEDDED_LIBRARY) + Vio *vio; + unsigned char *buff,*buff_end,*write_pos,*read_pos; + my_socket fd; /* For Perl DBI/dbd */ + /* + The following variable is set if we are doing several queries in one + command ( as in LOAD TABLE ... FROM MASTER ), + and do not want to confuse the client with OK at the wrong time + */ + unsigned long remain_in_buf,length, buf_length, where_b; + unsigned long max_packet,max_packet_size; + unsigned int pkt_nr,compress_pkt_nr; + unsigned int write_timeout, read_timeout, retry_count; + int fcntl; + unsigned int *return_status; + unsigned char reading_or_writing; + char save_char; + my_bool unused1; /* Please remove with the next incompatible ABI change. */ + my_bool unused2; /* Please remove with the next incompatible ABI change */ + my_bool compress; + my_bool unused3; /* Please remove with the next incompatible ABI change. */ + /* + Pointer to query object in query cache, do not equal NULL (0) for + queries in cache that have not stored its results yet + */ +#endif + /* + Unused, please remove with the next incompatible ABI change. + */ + unsigned char *unused; + unsigned int last_errno; + unsigned char error; + my_bool unused4; /* Please remove with the next incompatible ABI change. */ + my_bool unused5; /* Please remove with the next incompatible ABI change. */ + /** Client library error message buffer. Actually belongs to struct MYSQL. */ + char last_error[MYSQL_ERRMSG_SIZE]; + /** Client library sqlstate buffer. Set along with the error message. */ + char sqlstate[SQLSTATE_LENGTH+1]; + void *extension; +} NET; + + +#define packet_error (~(unsigned long) 0) + +enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY, + MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, + MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE, + MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP, + MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24, + MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, + MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, + MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR, + MYSQL_TYPE_BIT, + MYSQL_TYPE_NEWDECIMAL=246, + MYSQL_TYPE_ENUM=247, + MYSQL_TYPE_SET=248, + MYSQL_TYPE_TINY_BLOB=249, + MYSQL_TYPE_MEDIUM_BLOB=250, + MYSQL_TYPE_LONG_BLOB=251, + MYSQL_TYPE_BLOB=252, + MYSQL_TYPE_VAR_STRING=253, + MYSQL_TYPE_STRING=254, + MYSQL_TYPE_GEOMETRY=255, + MAX_NO_FIELD_TYPES /* Should always be last */ +}; + +/* For backward compatibility */ +#define CLIENT_MULTI_QUERIES CLIENT_MULTI_STATEMENTS +#define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL +#define FIELD_TYPE_NEWDECIMAL MYSQL_TYPE_NEWDECIMAL +#define FIELD_TYPE_TINY MYSQL_TYPE_TINY +#define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT +#define FIELD_TYPE_LONG MYSQL_TYPE_LONG +#define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT +#define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE +#define FIELD_TYPE_NULL MYSQL_TYPE_NULL +#define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP +#define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG +#define FIELD_TYPE_INT24 MYSQL_TYPE_INT24 +#define FIELD_TYPE_DATE MYSQL_TYPE_DATE +#define FIELD_TYPE_TIME MYSQL_TYPE_TIME +#define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME +#define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR +#define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE +#define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM +#define FIELD_TYPE_SET MYSQL_TYPE_SET +#define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB +#define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB +#define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB +#define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB +#define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING +#define FIELD_TYPE_STRING MYSQL_TYPE_STRING +#define FIELD_TYPE_CHAR MYSQL_TYPE_TINY +#define FIELD_TYPE_INTERVAL MYSQL_TYPE_ENUM +#define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY +#define FIELD_TYPE_BIT MYSQL_TYPE_BIT + + +/* Shutdown/kill enums and constants */ + +/* Bits for THD::killable. */ +#define MYSQL_SHUTDOWN_KILLABLE_CONNECT (unsigned char)(1 << 0) +#define MYSQL_SHUTDOWN_KILLABLE_TRANS (unsigned char)(1 << 1) +#define MYSQL_SHUTDOWN_KILLABLE_LOCK_TABLE (unsigned char)(1 << 2) +#define MYSQL_SHUTDOWN_KILLABLE_UPDATE (unsigned char)(1 << 3) + +enum mysql_enum_shutdown_level { + /* + We want levels to be in growing order of hardness (because we use number + comparisons). Note that DEFAULT does not respect the growing property, but + it's ok. + */ + SHUTDOWN_DEFAULT = 0, + /* wait for existing connections to finish */ + SHUTDOWN_WAIT_CONNECTIONS= MYSQL_SHUTDOWN_KILLABLE_CONNECT, + /* wait for existing trans to finish */ + SHUTDOWN_WAIT_TRANSACTIONS= MYSQL_SHUTDOWN_KILLABLE_TRANS, + /* wait for existing updates to finish (=> no partial MyISAM update) */ + SHUTDOWN_WAIT_UPDATES= MYSQL_SHUTDOWN_KILLABLE_UPDATE, + /* flush InnoDB buffers and other storage engines' buffers*/ + SHUTDOWN_WAIT_ALL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1), + /* don't flush InnoDB buffers, flush other storage engines' buffers*/ + SHUTDOWN_WAIT_CRITICAL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1) + 1, + /* Now the 2 levels of the KILL command */ +#if MYSQL_VERSION_ID >= 50000 + KILL_QUERY= 254, +#endif + KILL_CONNECTION= 255 +}; + + +enum enum_cursor_type +{ + CURSOR_TYPE_NO_CURSOR= 0, + CURSOR_TYPE_READ_ONLY= 1, + CURSOR_TYPE_FOR_UPDATE= 2, + CURSOR_TYPE_SCROLLABLE= 4 +}; + + +/* options for mysql_set_option */ +enum enum_mysql_set_option +{ + MYSQL_OPTION_MULTI_STATEMENTS_ON, + MYSQL_OPTION_MULTI_STATEMENTS_OFF +}; + +#define net_new_transaction(net) ((net)->pkt_nr=0) + +#ifdef __cplusplus +extern "C" { +#endif + +my_bool my_net_init(NET *net, Vio* vio); +void my_net_local_init(NET *net); +void net_end(NET *net); + void net_clear(NET *net, my_bool clear_buffer); +my_bool net_realloc(NET *net, size_t length); +my_bool net_flush(NET *net); +my_bool my_net_write(NET *net,const unsigned char *packet, size_t len); +my_bool net_write_command(NET *net,unsigned char command, + const unsigned char *header, size_t head_len, + const unsigned char *packet, size_t len); +int net_real_write(NET *net,const unsigned char *packet, size_t len); +unsigned long my_net_read(NET *net); + +#ifdef _global_h +void my_net_set_write_timeout(NET *net, uint timeout); +void my_net_set_read_timeout(NET *net, uint timeout); +#endif + +struct sockaddr; +int my_connect(my_socket s, const struct sockaddr *name, unsigned int namelen, + unsigned int timeout); +struct my_rnd_struct; + +#ifdef __cplusplus +} +#endif + + /* The following is for user defined functions */ + +enum Item_result +{ + STRING_RESULT=0, REAL_RESULT, INT_RESULT, ROW_RESULT, DECIMAL_RESULT +#ifdef MYSQL_SERVER + ,IMPOSSIBLE_RESULT /* Yes, we know this is ugly, don't tell us */ + ,MAX_NO_ITEM_RESULTS = IMPOSSIBLE_RESULT /* Should always be last */ +#endif +}; + +typedef struct st_udf_args +{ + unsigned int arg_count; /* Number of arguments */ + enum Item_result *arg_type; /* Pointer to item_results */ + char **args; /* Pointer to argument */ + unsigned long *lengths; /* Length of string arguments */ + char *maybe_null; /* Set to 1 for all maybe_null args */ + char **attributes; /* Pointer to attribute name */ + unsigned long *attribute_lengths; /* Length of attribute arguments */ + void *extension; +} UDF_ARGS; + + /* This holds information about the result */ + +typedef struct st_udf_init +{ + my_bool maybe_null; /* 1 if function can return NULL */ + unsigned int decimals; /* for real functions */ + unsigned long max_length; /* For string functions */ + char *ptr; /* free pointer for function data */ + my_bool const_item; /* 1 if function always returns the same value */ + void *extension; +} UDF_INIT; +/* + TODO: add a notion for determinism of the UDF. + See Item_udf_func::update_used_tables () +*/ + + /* Constants when using compression */ +#define NET_HEADER_SIZE 4 /* standard header size */ +#define COMP_HEADER_SIZE 3 /* compression header extra size */ + + /* Prototypes to password functions */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* + These functions are used for authentication by client and server and + implemented in sql/password.c +*/ + +void create_random_string(char *to, unsigned int length, + struct my_rnd_struct *rand_st); + +void hash_password(unsigned long *to, const char *password, unsigned int password_len); +void make_scrambled_password_323(char *to, const char *password); +void scramble_323(char *to, const char *message, const char *password); +my_bool check_scramble_323(const char *, const char *message, + unsigned long *salt); +void get_salt_from_password_323(unsigned long *res, const char *password); +void make_password_from_salt_323(char *to, const unsigned long *salt); + +void make_scrambled_password(char *to, const char *password); +void scramble(char *to, const char *message, const char *password); +my_bool check_scramble(const char *reply, const char *message, + const unsigned char *hash_stage2); +void get_salt_from_password(unsigned char *res, const char *password); +void make_password_from_salt(char *to, const unsigned char *hash_stage2); +char *octet2hex(char *to, const char *str, unsigned int len); + +/* end of password.c */ + +char *get_tty_password(const char *opt_message); +const char *mysql_errno_to_sqlstate(unsigned int mysql_errno); + +/* Some other useful functions */ + +my_bool my_thread_init(void); +void my_thread_end(void); + +#ifdef _global_h +ulong STDCALL net_field_length(uchar **packet); +my_ulonglong net_field_length_ll(uchar **packet); +uchar *net_store_length(uchar *pkg, ulonglong length); +#endif + +#ifdef __cplusplus +} +#endif + +#define NULL_LENGTH ((unsigned long) ~0) /* For net_store_length */ +#define MYSQL_STMT_HEADER 4 +#define MYSQL_LONG_DATA_HEADER 6 + +#define NOT_FIXED_DEC 31 +#endif diff --git a/mysql_incl/mysql_time.h b/mysql_incl/mysql_time.h new file mode 100644 index 0000000..0a3f17a --- /dev/null +++ b/mysql_incl/mysql_time.h @@ -0,0 +1,55 @@ +/* Copyright (C) 2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _mysql_time_h_ +#define _mysql_time_h_ + +/* + Time declarations shared between the server and client API: + you should not add anything to this header unless it's used + (and hence should be visible) in mysql.h. + If you're looking for a place to add new time-related declaration, + it's most likely my_time.h. See also "C API Handling of Date + and Time Values" chapter in documentation. +*/ + +enum enum_mysql_timestamp_type +{ + MYSQL_TIMESTAMP_NONE= -2, MYSQL_TIMESTAMP_ERROR= -1, + MYSQL_TIMESTAMP_DATE= 0, MYSQL_TIMESTAMP_DATETIME= 1, MYSQL_TIMESTAMP_TIME= 2 +}; + + +/* + Structure which is used to represent datetime values inside MySQL. + + We assume that values in this structure are normalized, i.e. year <= 9999, + month <= 12, day <= 31, hour <= 23, hour <= 59, hour <= 59. Many functions + in server such as my_system_gmt_sec() or make_time() family of functions + rely on this (actually now usage of make_*() family relies on a bit weaker + restriction). Also functions that produce MYSQL_TIME as result ensure this. + There is one exception to this rule though if this structure holds time + value (time_type == MYSQL_TIMESTAMP_TIME) days and hour member can hold + bigger values. +*/ +typedef struct st_mysql_time +{ + unsigned int year, month, day, hour, minute, second; + unsigned long second_part; + my_bool neg; + enum enum_mysql_timestamp_type time_type; +} MYSQL_TIME; + +#endif /* _mysql_time_h_ */ diff --git a/mysql_incl/mysql_version.h b/mysql_incl/mysql_version.h new file mode 100644 index 0000000..3f052b8 --- /dev/null +++ b/mysql_incl/mysql_version.h @@ -0,0 +1,26 @@ +/* Copyright Abandoned 1996, 1999, 2001 MySQL AB + This file is public domain and comes with NO WARRANTY of any kind */ + +/* Version numbers for protocol & mysqld */ + +#ifndef _mysql_version_h +#define _mysql_version_h + +#ifdef _CUSTOMCONFIG_ +# include +#else +# define PROTOCOL_VERSION 10 +# define MYSQL_SERVER_VERSION "6.0.0" +# define MYSQL_VERSION_ID 60000 +# define MYSQL_PORT 3306 +# define MYSQL_PORT_DEFAULT 0 +# define MYSQL_UNIX_ADDR "/tmp/mysql.sock" +# define MYSQL_CONFIG_NAME "my" +# define MYSQL_COMPILATION_COMMENT "Source distribution" +#endif /* _CUSTOMCONFIG_ */ + +#ifndef LICENSE +# define LICENSE GPL +#endif /* LICENSE */ + +#endif /* _mysql_version_h */ diff --git a/mysql_incl/mysqld_error.h b/mysql_incl/mysqld_error.h new file mode 100644 index 0000000..653e583 --- /dev/null +++ b/mysql_incl/mysqld_error.h @@ -0,0 +1,730 @@ +/* Autogenerated file, please don't edit */ + +#define ER_ERROR_FIRST 1000 +#define ER_HASHCHK 1000 +#define ER_NISAMCHK 1001 +#define ER_NO 1002 +#define ER_YES 1003 +#define ER_CANT_CREATE_FILE 1004 +#define ER_CANT_CREATE_TABLE 1005 +#define ER_CANT_CREATE_DB 1006 +#define ER_DB_CREATE_EXISTS 1007 +#define ER_DB_DROP_EXISTS 1008 +#define ER_DB_DROP_DELETE 1009 +#define ER_DB_DROP_RMDIR 1010 +#define ER_CANT_DELETE_FILE 1011 +#define ER_CANT_FIND_SYSTEM_REC 1012 +#define ER_CANT_GET_STAT 1013 +#define ER_CANT_GET_WD 1014 +#define ER_CANT_LOCK 1015 +#define ER_CANT_OPEN_FILE 1016 +#define ER_FILE_NOT_FOUND 1017 +#define ER_CANT_READ_DIR 1018 +#define ER_CANT_SET_WD 1019 +#define ER_CHECKREAD 1020 +#define ER_DISK_FULL 1021 +#define ER_DUP_KEY 1022 +#define ER_ERROR_ON_CLOSE 1023 +#define ER_ERROR_ON_READ 1024 +#define ER_ERROR_ON_RENAME 1025 +#define ER_ERROR_ON_WRITE 1026 +#define ER_FILE_USED 1027 +#define ER_FILSORT_ABORT 1028 +#define ER_FORM_NOT_FOUND 1029 +#define ER_GET_ERRNO 1030 +#define ER_ILLEGAL_HA 1031 +#define ER_KEY_NOT_FOUND 1032 +#define ER_NOT_FORM_FILE 1033 +#define ER_NOT_KEYFILE 1034 +#define ER_OLD_KEYFILE 1035 +#define ER_OPEN_AS_READONLY 1036 +#define ER_OUTOFMEMORY 1037 +#define ER_OUT_OF_SORTMEMORY 1038 +#define ER_UNEXPECTED_EOF 1039 +#define ER_CON_COUNT_ERROR 1040 +#define ER_OUT_OF_RESOURCES 1041 +#define ER_BAD_HOST_ERROR 1042 +#define ER_HANDSHAKE_ERROR 1043 +#define ER_DBACCESS_DENIED_ERROR 1044 +#define ER_ACCESS_DENIED_ERROR 1045 +#define ER_NO_DB_ERROR 1046 +#define ER_UNKNOWN_COM_ERROR 1047 +#define ER_BAD_NULL_ERROR 1048 +#define ER_BAD_DB_ERROR 1049 +#define ER_TABLE_EXISTS_ERROR 1050 +#define ER_BAD_TABLE_ERROR 1051 +#define ER_NON_UNIQ_ERROR 1052 +#define ER_SERVER_SHUTDOWN 1053 +#define ER_BAD_FIELD_ERROR 1054 +#define ER_WRONG_FIELD_WITH_GROUP 1055 +#define ER_WRONG_GROUP_FIELD 1056 +#define ER_WRONG_SUM_SELECT 1057 +#define ER_WRONG_VALUE_COUNT 1058 +#define ER_TOO_LONG_IDENT 1059 +#define ER_DUP_FIELDNAME 1060 +#define ER_DUP_KEYNAME 1061 +#define ER_DUP_ENTRY 1062 +#define ER_WRONG_FIELD_SPEC 1063 +#define ER_PARSE_ERROR 1064 +#define ER_EMPTY_QUERY 1065 +#define ER_NONUNIQ_TABLE 1066 +#define ER_INVALID_DEFAULT 1067 +#define ER_MULTIPLE_PRI_KEY 1068 +#define ER_TOO_MANY_KEYS 1069 +#define ER_TOO_MANY_KEY_PARTS 1070 +#define ER_TOO_LONG_KEY 1071 +#define ER_KEY_COLUMN_DOES_NOT_EXITS 1072 +#define ER_BLOB_USED_AS_KEY 1073 +#define ER_TOO_BIG_FIELDLENGTH 1074 +#define ER_WRONG_AUTO_KEY 1075 +#define ER_READY 1076 +#define ER_NORMAL_SHUTDOWN 1077 +#define ER_GOT_SIGNAL 1078 +#define ER_SHUTDOWN_COMPLETE 1079 +#define ER_FORCING_CLOSE 1080 +#define ER_IPSOCK_ERROR 1081 +#define ER_NO_SUCH_INDEX 1082 +#define ER_WRONG_FIELD_TERMINATORS 1083 +#define ER_BLOBS_AND_NO_TERMINATED 1084 +#define ER_TEXTFILE_NOT_READABLE 1085 +#define ER_FILE_EXISTS_ERROR 1086 +#define ER_LOAD_INFO 1087 +#define ER_ALTER_INFO 1088 +#define ER_WRONG_SUB_KEY 1089 +#define ER_CANT_REMOVE_ALL_FIELDS 1090 +#define ER_CANT_DROP_FIELD_OR_KEY 1091 +#define ER_INSERT_INFO 1092 +#define ER_UPDATE_TABLE_USED 1093 +#define ER_NO_SUCH_THREAD 1094 +#define ER_KILL_DENIED_ERROR 1095 +#define ER_NO_TABLES_USED 1096 +#define ER_TOO_BIG_SET 1097 +#define ER_NO_UNIQUE_LOGFILE 1098 +#define ER_TABLE_NOT_LOCKED_FOR_WRITE 1099 +#define ER_TABLE_NOT_LOCKED 1100 +#define ER_BLOB_CANT_HAVE_DEFAULT 1101 +#define ER_WRONG_DB_NAME 1102 +#define ER_WRONG_TABLE_NAME 1103 +#define ER_TOO_BIG_SELECT 1104 +#define ER_UNKNOWN_ERROR 1105 +#define ER_UNKNOWN_PROCEDURE 1106 +#define ER_WRONG_PARAMCOUNT_TO_PROCEDURE 1107 +#define ER_WRONG_PARAMETERS_TO_PROCEDURE 1108 +#define ER_UNKNOWN_TABLE 1109 +#define ER_FIELD_SPECIFIED_TWICE 1110 +#define ER_INVALID_GROUP_FUNC_USE 1111 +#define ER_UNSUPPORTED_EXTENSION 1112 +#define ER_TABLE_MUST_HAVE_COLUMNS 1113 +#define ER_RECORD_FILE_FULL 1114 +#define ER_UNKNOWN_CHARACTER_SET 1115 +#define ER_TOO_MANY_TABLES 1116 +#define ER_TOO_MANY_FIELDS 1117 +#define ER_TOO_BIG_ROWSIZE 1118 +#define ER_STACK_OVERRUN 1119 +#define ER_WRONG_OUTER_JOIN 1120 +#define ER_NULL_COLUMN_IN_INDEX 1121 +#define ER_CANT_FIND_UDF 1122 +#define ER_CANT_INITIALIZE_UDF 1123 +#define ER_UDF_NO_PATHS 1124 +#define ER_UDF_EXISTS 1125 +#define ER_CANT_OPEN_LIBRARY 1126 +#define ER_CANT_FIND_DL_ENTRY 1127 +#define ER_FUNCTION_NOT_DEFINED 1128 +#define ER_HOST_IS_BLOCKED 1129 +#define ER_HOST_NOT_PRIVILEGED 1130 +#define ER_PASSWORD_ANONYMOUS_USER 1131 +#define ER_PASSWORD_NOT_ALLOWED 1132 +#define ER_PASSWORD_NO_MATCH 1133 +#define ER_UPDATE_INFO 1134 +#define ER_CANT_CREATE_THREAD 1135 +#define ER_WRONG_VALUE_COUNT_ON_ROW 1136 +#define ER_CANT_REOPEN_TABLE 1137 +#define ER_INVALID_USE_OF_NULL 1138 +#define ER_REGEXP_ERROR 1139 +#define ER_MIX_OF_GROUP_FUNC_AND_FIELDS 1140 +#define ER_NONEXISTING_GRANT 1141 +#define ER_TABLEACCESS_DENIED_ERROR 1142 +#define ER_COLUMNACCESS_DENIED_ERROR 1143 +#define ER_ILLEGAL_GRANT_FOR_TABLE 1144 +#define ER_GRANT_WRONG_HOST_OR_USER 1145 +#define ER_NO_SUCH_TABLE 1146 +#define ER_NONEXISTING_TABLE_GRANT 1147 +#define ER_NOT_ALLOWED_COMMAND 1148 +#define ER_SYNTAX_ERROR 1149 +#define ER_DELAYED_CANT_CHANGE_LOCK 1150 +#define ER_TOO_MANY_DELAYED_THREADS 1151 +#define ER_ABORTING_CONNECTION 1152 +#define ER_NET_PACKET_TOO_LARGE 1153 +#define ER_NET_READ_ERROR_FROM_PIPE 1154 +#define ER_NET_FCNTL_ERROR 1155 +#define ER_NET_PACKETS_OUT_OF_ORDER 1156 +#define ER_NET_UNCOMPRESS_ERROR 1157 +#define ER_NET_READ_ERROR 1158 +#define ER_NET_READ_INTERRUPTED 1159 +#define ER_NET_ERROR_ON_WRITE 1160 +#define ER_NET_WRITE_INTERRUPTED 1161 +#define ER_TOO_LONG_STRING 1162 +#define ER_TABLE_CANT_HANDLE_BLOB 1163 +#define ER_TABLE_CANT_HANDLE_AUTO_INCREMENT 1164 +#define ER_DELAYED_INSERT_TABLE_LOCKED 1165 +#define ER_WRONG_COLUMN_NAME 1166 +#define ER_WRONG_KEY_COLUMN 1167 +#define ER_WRONG_MRG_TABLE 1168 +#define ER_DUP_UNIQUE 1169 +#define ER_BLOB_KEY_WITHOUT_LENGTH 1170 +#define ER_PRIMARY_CANT_HAVE_NULL 1171 +#define ER_TOO_MANY_ROWS 1172 +#define ER_REQUIRES_PRIMARY_KEY 1173 +#define ER_NO_RAID_COMPILED 1174 +#define ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE 1175 +#define ER_KEY_DOES_NOT_EXITS 1176 +#define ER_CHECK_NO_SUCH_TABLE 1177 +#define ER_CHECK_NOT_IMPLEMENTED 1178 +#define ER_CANT_DO_THIS_DURING_AN_TRANSACTION 1179 +#define ER_ERROR_DURING_COMMIT 1180 +#define ER_ERROR_DURING_ROLLBACK 1181 +#define ER_ERROR_DURING_FLUSH_LOGS 1182 +#define ER_ERROR_DURING_CHECKPOINT 1183 +#define ER_NEW_ABORTING_CONNECTION 1184 +#define ER_DUMP_NOT_IMPLEMENTED 1185 +#define ER_FLUSH_MASTER_BINLOG_CLOSED 1186 +#define ER_INDEX_REBUILD 1187 +#define ER_MASTER 1188 +#define ER_MASTER_NET_READ 1189 +#define ER_MASTER_NET_WRITE 1190 +#define ER_FT_MATCHING_KEY_NOT_FOUND 1191 +#define ER_LOCK_OR_ACTIVE_TRANSACTION 1192 +#define ER_UNKNOWN_SYSTEM_VARIABLE 1193 +#define ER_CRASHED_ON_USAGE 1194 +#define ER_CRASHED_ON_REPAIR 1195 +#define ER_WARNING_NOT_COMPLETE_ROLLBACK 1196 +#define ER_TRANS_CACHE_FULL 1197 +#define ER_SLAVE_MUST_STOP 1198 +#define ER_SLAVE_NOT_RUNNING 1199 +#define ER_BAD_SLAVE 1200 +#define ER_MASTER_INFO 1201 +#define ER_SLAVE_THREAD 1202 +#define ER_TOO_MANY_USER_CONNECTIONS 1203 +#define ER_SET_CONSTANTS_ONLY 1204 +#define ER_LOCK_WAIT_TIMEOUT 1205 +#define ER_LOCK_TABLE_FULL 1206 +#define ER_READ_ONLY_TRANSACTION 1207 +#define ER_DROP_DB_WITH_READ_LOCK 1208 +#define ER_CREATE_DB_WITH_READ_LOCK 1209 +#define ER_WRONG_ARGUMENTS 1210 +#define ER_NO_PERMISSION_TO_CREATE_USER 1211 +#define ER_UNION_TABLES_IN_DIFFERENT_DIR 1212 +#define ER_LOCK_DEADLOCK 1213 +#define ER_TABLE_CANT_HANDLE_FT 1214 +#define ER_CANNOT_ADD_FOREIGN 1215 +#define ER_NO_REFERENCED_ROW 1216 +#define ER_ROW_IS_REFERENCED 1217 +#define ER_CONNECT_TO_MASTER 1218 +#define ER_QUERY_ON_MASTER 1219 +#define ER_ERROR_WHEN_EXECUTING_COMMAND 1220 +#define ER_WRONG_USAGE 1221 +#define ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT 1222 +#define ER_CANT_UPDATE_WITH_READLOCK 1223 +#define ER_MIXING_NOT_ALLOWED 1224 +#define ER_DUP_ARGUMENT 1225 +#define ER_USER_LIMIT_REACHED 1226 +#define ER_SPECIFIC_ACCESS_DENIED_ERROR 1227 +#define ER_LOCAL_VARIABLE 1228 +#define ER_GLOBAL_VARIABLE 1229 +#define ER_NO_DEFAULT 1230 +#define ER_WRONG_VALUE_FOR_VAR 1231 +#define ER_WRONG_TYPE_FOR_VAR 1232 +#define ER_VAR_CANT_BE_READ 1233 +#define ER_CANT_USE_OPTION_HERE 1234 +#define ER_NOT_SUPPORTED_YET 1235 +#define ER_MASTER_FATAL_ERROR_READING_BINLOG 1236 +#define ER_SLAVE_IGNORED_TABLE 1237 +#define ER_INCORRECT_GLOBAL_LOCAL_VAR 1238 +#define ER_WRONG_FK_DEF 1239 +#define ER_KEY_REF_DO_NOT_MATCH_TABLE_REF 1240 +#define ER_OPERAND_COLUMNS 1241 +#define ER_SUBQUERY_NO_1_ROW 1242 +#define ER_UNKNOWN_STMT_HANDLER 1243 +#define ER_CORRUPT_HELP_DB 1244 +#define ER_CYCLIC_REFERENCE 1245 +#define ER_AUTO_CONVERT 1246 +#define ER_ILLEGAL_REFERENCE 1247 +#define ER_DERIVED_MUST_HAVE_ALIAS 1248 +#define ER_SELECT_REDUCED 1249 +#define ER_TABLENAME_NOT_ALLOWED_HERE 1250 +#define ER_NOT_SUPPORTED_AUTH_MODE 1251 +#define ER_SPATIAL_CANT_HAVE_NULL 1252 +#define ER_COLLATION_CHARSET_MISMATCH 1253 +#define ER_SLAVE_WAS_RUNNING 1254 +#define ER_SLAVE_WAS_NOT_RUNNING 1255 +#define ER_TOO_BIG_FOR_UNCOMPRESS 1256 +#define ER_ZLIB_Z_MEM_ERROR 1257 +#define ER_ZLIB_Z_BUF_ERROR 1258 +#define ER_ZLIB_Z_DATA_ERROR 1259 +#define ER_CUT_VALUE_GROUP_CONCAT 1260 +#define ER_WARN_TOO_FEW_RECORDS 1261 +#define ER_WARN_TOO_MANY_RECORDS 1262 +#define ER_WARN_NULL_TO_NOTNULL 1263 +#define ER_WARN_DATA_OUT_OF_RANGE 1264 +#define WARN_DATA_TRUNCATED 1265 +#define ER_WARN_USING_OTHER_HANDLER 1266 +#define ER_CANT_AGGREGATE_2COLLATIONS 1267 +#define ER_DROP_USER 1268 +#define ER_REVOKE_GRANTS 1269 +#define ER_CANT_AGGREGATE_3COLLATIONS 1270 +#define ER_CANT_AGGREGATE_NCOLLATIONS 1271 +#define ER_VARIABLE_IS_NOT_STRUCT 1272 +#define ER_UNKNOWN_COLLATION 1273 +#define ER_SLAVE_IGNORED_SSL_PARAMS 1274 +#define ER_SERVER_IS_IN_SECURE_AUTH_MODE 1275 +#define ER_WARN_FIELD_RESOLVED 1276 +#define ER_BAD_SLAVE_UNTIL_COND 1277 +#define ER_MISSING_SKIP_SLAVE 1278 +#define ER_UNTIL_COND_IGNORED 1279 +#define ER_WRONG_NAME_FOR_INDEX 1280 +#define ER_WRONG_NAME_FOR_CATALOG 1281 +#define ER_WARN_QC_RESIZE 1282 +#define ER_BAD_FT_COLUMN 1283 +#define ER_UNKNOWN_KEY_CACHE 1284 +#define ER_WARN_HOSTNAME_WONT_WORK 1285 +#define ER_UNKNOWN_STORAGE_ENGINE 1286 +#define ER_WARN_DEPRECATED_SYNTAX 1287 +#define ER_NON_UPDATABLE_TABLE 1288 +#define ER_FEATURE_DISABLED 1289 +#define ER_OPTION_PREVENTS_STATEMENT 1290 +#define ER_DUPLICATED_VALUE_IN_TYPE 1291 +#define ER_TRUNCATED_WRONG_VALUE 1292 +#define ER_TOO_MUCH_AUTO_TIMESTAMP_COLS 1293 +#define ER_INVALID_ON_UPDATE 1294 +#define ER_UNSUPPORTED_PS 1295 +#define ER_GET_ERRMSG 1296 +#define ER_GET_TEMPORARY_ERRMSG 1297 +#define ER_UNKNOWN_TIME_ZONE 1298 +#define ER_WARN_INVALID_TIMESTAMP 1299 +#define ER_INVALID_CHARACTER_STRING 1300 +#define ER_WARN_ALLOWED_PACKET_OVERFLOWED 1301 +#define ER_CONFLICTING_DECLARATIONS 1302 +#define ER_SP_NO_RECURSIVE_CREATE 1303 +#define ER_SP_ALREADY_EXISTS 1304 +#define ER_SP_DOES_NOT_EXIST 1305 +#define ER_SP_DROP_FAILED 1306 +#define ER_SP_STORE_FAILED 1307 +#define ER_SP_LILABEL_MISMATCH 1308 +#define ER_SP_LABEL_REDEFINE 1309 +#define ER_SP_LABEL_MISMATCH 1310 +#define ER_SP_UNINIT_VAR 1311 +#define ER_SP_BADSELECT 1312 +#define ER_SP_BADRETURN 1313 +#define ER_SP_BADSTATEMENT 1314 +#define ER_UPDATE_LOG_DEPRECATED_IGNORED 1315 +#define ER_UPDATE_LOG_DEPRECATED_TRANSLATED 1316 +#define ER_QUERY_INTERRUPTED 1317 +#define ER_SP_WRONG_NO_OF_ARGS 1318 +#define ER_SP_COND_MISMATCH 1319 +#define ER_SP_NORETURN 1320 +#define ER_SP_NORETURNEND 1321 +#define ER_SP_BAD_CURSOR_QUERY 1322 +#define ER_SP_BAD_CURSOR_SELECT 1323 +#define ER_SP_CURSOR_MISMATCH 1324 +#define ER_SP_CURSOR_ALREADY_OPEN 1325 +#define ER_SP_CURSOR_NOT_OPEN 1326 +#define ER_SP_UNDECLARED_VAR 1327 +#define ER_SP_WRONG_NO_OF_FETCH_ARGS 1328 +#define ER_SP_FETCH_NO_DATA 1329 +#define ER_SP_DUP_PARAM 1330 +#define ER_SP_DUP_VAR 1331 +#define ER_SP_DUP_COND 1332 +#define ER_SP_DUP_CURS 1333 +#define ER_SP_CANT_ALTER 1334 +#define ER_SP_SUBSELECT_NYI 1335 +#define ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG 1336 +#define ER_SP_VARCOND_AFTER_CURSHNDLR 1337 +#define ER_SP_CURSOR_AFTER_HANDLER 1338 +#define ER_SP_CASE_NOT_FOUND 1339 +#define ER_FPARSER_TOO_BIG_FILE 1340 +#define ER_FPARSER_BAD_HEADER 1341 +#define ER_FPARSER_EOF_IN_COMMENT 1342 +#define ER_FPARSER_ERROR_IN_PARAMETER 1343 +#define ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER 1344 +#define ER_VIEW_NO_EXPLAIN 1345 +#define ER_FRM_UNKNOWN_TYPE 1346 +#define ER_WRONG_OBJECT 1347 +#define ER_NONUPDATEABLE_COLUMN 1348 +#define ER_VIEW_SELECT_DERIVED 1349 +#define ER_VIEW_SELECT_CLAUSE 1350 +#define ER_VIEW_SELECT_VARIABLE 1351 +#define ER_VIEW_SELECT_TMPTABLE 1352 +#define ER_VIEW_WRONG_LIST 1353 +#define ER_WARN_VIEW_MERGE 1354 +#define ER_WARN_VIEW_WITHOUT_KEY 1355 +#define ER_VIEW_INVALID 1356 +#define ER_SP_NO_DROP_SP 1357 +#define ER_SP_GOTO_IN_HNDLR 1358 +#define ER_TRG_ALREADY_EXISTS 1359 +#define ER_TRG_DOES_NOT_EXIST 1360 +#define ER_TRG_ON_VIEW_OR_TEMP_TABLE 1361 +#define ER_TRG_CANT_CHANGE_ROW 1362 +#define ER_TRG_NO_SUCH_ROW_IN_TRG 1363 +#define ER_NO_DEFAULT_FOR_FIELD 1364 +#define ER_DIVISION_BY_ZERO 1365 +#define ER_TRUNCATED_WRONG_VALUE_FOR_FIELD 1366 +#define ER_ILLEGAL_VALUE_FOR_TYPE 1367 +#define ER_VIEW_NONUPD_CHECK 1368 +#define ER_VIEW_CHECK_FAILED 1369 +#define ER_PROCACCESS_DENIED_ERROR 1370 +#define ER_RELAY_LOG_FAIL 1371 +#define ER_PASSWD_LENGTH 1372 +#define ER_UNKNOWN_TARGET_BINLOG 1373 +#define ER_IO_ERR_LOG_INDEX_READ 1374 +#define ER_BINLOG_PURGE_PROHIBITED 1375 +#define ER_FSEEK_FAIL 1376 +#define ER_BINLOG_PURGE_FATAL_ERR 1377 +#define ER_LOG_IN_USE 1378 +#define ER_LOG_PURGE_UNKNOWN_ERR 1379 +#define ER_RELAY_LOG_INIT 1380 +#define ER_NO_BINARY_LOGGING 1381 +#define ER_RESERVED_SYNTAX 1382 +#define ER_WSAS_FAILED 1383 +#define ER_DIFF_GROUPS_PROC 1384 +#define ER_NO_GROUP_FOR_PROC 1385 +#define ER_ORDER_WITH_PROC 1386 +#define ER_LOGGING_PROHIBIT_CHANGING_OF 1387 +#define ER_NO_FILE_MAPPING 1388 +#define ER_WRONG_MAGIC 1389 +#define ER_PS_MANY_PARAM 1390 +#define ER_KEY_PART_0 1391 +#define ER_VIEW_CHECKSUM 1392 +#define ER_VIEW_MULTIUPDATE 1393 +#define ER_VIEW_NO_INSERT_FIELD_LIST 1394 +#define ER_VIEW_DELETE_MERGE_VIEW 1395 +#define ER_CANNOT_USER 1396 +#define ER_XAER_NOTA 1397 +#define ER_XAER_INVAL 1398 +#define ER_XAER_RMFAIL 1399 +#define ER_XAER_OUTSIDE 1400 +#define ER_XAER_RMERR 1401 +#define ER_XA_RBROLLBACK 1402 +#define ER_NONEXISTING_PROC_GRANT 1403 +#define ER_PROC_AUTO_GRANT_FAIL 1404 +#define ER_PROC_AUTO_REVOKE_FAIL 1405 +#define ER_DATA_TOO_LONG 1406 +#define ER_SP_BAD_SQLSTATE 1407 +#define ER_STARTUP 1408 +#define ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR 1409 +#define ER_CANT_CREATE_USER_WITH_GRANT 1410 +#define ER_WRONG_VALUE_FOR_TYPE 1411 +#define ER_TABLE_DEF_CHANGED 1412 +#define ER_SP_DUP_HANDLER 1413 +#define ER_SP_NOT_VAR_ARG 1414 +#define ER_SP_NO_RETSET 1415 +#define ER_CANT_CREATE_GEOMETRY_OBJECT 1416 +#define ER_FAILED_ROUTINE_BREAK_BINLOG 1417 +#define ER_BINLOG_UNSAFE_ROUTINE 1418 +#define ER_BINLOG_CREATE_ROUTINE_NEED_SUPER 1419 +#define ER_EXEC_STMT_WITH_OPEN_CURSOR 1420 +#define ER_STMT_HAS_NO_OPEN_CURSOR 1421 +#define ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG 1422 +#define ER_NO_DEFAULT_FOR_VIEW_FIELD 1423 +#define ER_SP_NO_RECURSION 1424 +#define ER_TOO_BIG_SCALE 1425 +#define ER_TOO_BIG_PRECISION 1426 +#define ER_M_BIGGER_THAN_D 1427 +#define ER_WRONG_LOCK_OF_SYSTEM_TABLE 1428 +#define ER_CONNECT_TO_FOREIGN_DATA_SOURCE 1429 +#define ER_QUERY_ON_FOREIGN_DATA_SOURCE 1430 +#define ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST 1431 +#define ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE 1432 +#define ER_FOREIGN_DATA_STRING_INVALID 1433 +#define ER_CANT_CREATE_FEDERATED_TABLE 1434 +#define ER_TRG_IN_WRONG_SCHEMA 1435 +#define ER_STACK_OVERRUN_NEED_MORE 1436 +#define ER_TOO_LONG_BODY 1437 +#define ER_WARN_CANT_DROP_DEFAULT_KEYCACHE 1438 +#define ER_TOO_BIG_DISPLAYWIDTH 1439 +#define ER_XAER_DUPID 1440 +#define ER_DATETIME_FUNCTION_OVERFLOW 1441 +#define ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG 1442 +#define ER_VIEW_PREVENT_UPDATE 1443 +#define ER_PS_NO_RECURSION 1444 +#define ER_SP_CANT_SET_AUTOCOMMIT 1445 +#define ER_MALFORMED_DEFINER 1446 +#define ER_VIEW_FRM_NO_USER 1447 +#define ER_VIEW_OTHER_USER 1448 +#define ER_NO_SUCH_USER 1449 +#define ER_FORBID_SCHEMA_CHANGE 1450 +#define ER_ROW_IS_REFERENCED_2 1451 +#define ER_NO_REFERENCED_ROW_2 1452 +#define ER_SP_BAD_VAR_SHADOW 1453 +#define ER_TRG_NO_DEFINER 1454 +#define ER_OLD_FILE_FORMAT 1455 +#define ER_SP_RECURSION_LIMIT 1456 +#define ER_SP_PROC_TABLE_CORRUPT 1457 +#define ER_SP_WRONG_NAME 1458 +#define ER_TABLE_NEEDS_UPGRADE 1459 +#define ER_SP_NO_AGGREGATE 1460 +#define ER_MAX_PREPARED_STMT_COUNT_REACHED 1461 +#define ER_VIEW_RECURSIVE 1462 +#define ER_NON_GROUPING_FIELD_USED 1463 +#define ER_TABLE_CANT_HANDLE_SPKEYS 1464 +#define ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA 1465 +#define ER_REMOVED_SPACES 1466 +#define ER_AUTOINC_READ_FAILED 1467 +#define ER_USERNAME 1468 +#define ER_HOSTNAME 1469 +#define ER_WRONG_STRING_LENGTH 1470 +#define ER_NON_INSERTABLE_TABLE 1471 +#define ER_ADMIN_WRONG_MRG_TABLE 1472 +#define ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT 1473 +#define ER_NAME_BECOMES_EMPTY 1474 +#define ER_AMBIGUOUS_FIELD_TERM 1475 +#define ER_FOREIGN_SERVER_EXISTS 1476 +#define ER_FOREIGN_SERVER_DOESNT_EXIST 1477 +#define ER_ILLEGAL_HA_CREATE_OPTION 1478 +#define ER_PARTITION_REQUIRES_VALUES_ERROR 1479 +#define ER_PARTITION_WRONG_VALUES_ERROR 1480 +#define ER_PARTITION_MAXVALUE_ERROR 1481 +#define ER_PARTITION_SUBPARTITION_ERROR 1482 +#define ER_PARTITION_SUBPART_MIX_ERROR 1483 +#define ER_PARTITION_WRONG_NO_PART_ERROR 1484 +#define ER_PARTITION_WRONG_NO_SUBPART_ERROR 1485 +#define ER_CONST_EXPR_IN_PARTITION_FUNC_ERROR 1486 +#define ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR 1487 +#define ER_FIELD_NOT_FOUND_PART_ERROR 1488 +#define ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR 1489 +#define ER_INCONSISTENT_PARTITION_INFO_ERROR 1490 +#define ER_PARTITION_FUNC_NOT_ALLOWED_ERROR 1491 +#define ER_PARTITIONS_MUST_BE_DEFINED_ERROR 1492 +#define ER_RANGE_NOT_INCREASING_ERROR 1493 +#define ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR 1494 +#define ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR 1495 +#define ER_PARTITION_ENTRY_ERROR 1496 +#define ER_MIX_HANDLER_ERROR 1497 +#define ER_PARTITION_NOT_DEFINED_ERROR 1498 +#define ER_TOO_MANY_PARTITIONS_ERROR 1499 +#define ER_SUBPARTITION_ERROR 1500 +#define ER_CANT_CREATE_HANDLER_FILE 1501 +#define ER_BLOB_FIELD_IN_PART_FUNC_ERROR 1502 +#define ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF 1503 +#define ER_NO_PARTS_ERROR 1504 +#define ER_PARTITION_MGMT_ON_NONPARTITIONED 1505 +#define ER_FOREIGN_KEY_ON_PARTITIONED 1506 +#define ER_DROP_PARTITION_NON_EXISTENT 1507 +#define ER_DROP_LAST_PARTITION 1508 +#define ER_COALESCE_ONLY_ON_HASH_PARTITION 1509 +#define ER_REORG_HASH_ONLY_ON_SAME_NO 1510 +#define ER_REORG_NO_PARAM_ERROR 1511 +#define ER_ONLY_ON_RANGE_LIST_PARTITION 1512 +#define ER_ADD_PARTITION_SUBPART_ERROR 1513 +#define ER_ADD_PARTITION_NO_NEW_PARTITION 1514 +#define ER_COALESCE_PARTITION_NO_PARTITION 1515 +#define ER_REORG_PARTITION_NOT_EXIST 1516 +#define ER_SAME_NAME_PARTITION 1517 +#define ER_NO_BINLOG_ERROR 1518 +#define ER_CONSECUTIVE_REORG_PARTITIONS 1519 +#define ER_REORG_OUTSIDE_RANGE 1520 +#define ER_PARTITION_FUNCTION_FAILURE 1521 +#define ER_PART_STATE_ERROR 1522 +#define ER_LIMITED_PART_RANGE 1523 +#define ER_PLUGIN_IS_NOT_LOADED 1524 +#define ER_WRONG_VALUE 1525 +#define ER_NO_PARTITION_FOR_GIVEN_VALUE 1526 +#define ER_FILEGROUP_OPTION_ONLY_ONCE 1527 +#define ER_CREATE_FILEGROUP_FAILED 1528 +#define ER_DROP_FILEGROUP_FAILED 1529 +#define ER_TABLESPACE_AUTO_EXTEND_ERROR 1530 +#define ER_WRONG_SIZE_NUMBER 1531 +#define ER_SIZE_OVERFLOW_ERROR 1532 +#define ER_ALTER_FILEGROUP_FAILED 1533 +#define ER_BINLOG_ROW_LOGGING_FAILED 1534 +#define ER_BINLOG_ROW_WRONG_TABLE_DEF 1535 +#define ER_BINLOG_ROW_RBR_TO_SBR 1536 +#define ER_EVENT_ALREADY_EXISTS 1537 +#define ER_EVENT_STORE_FAILED 1538 +#define ER_EVENT_DOES_NOT_EXIST 1539 +#define ER_EVENT_CANT_ALTER 1540 +#define ER_EVENT_DROP_FAILED 1541 +#define ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG 1542 +#define ER_EVENT_ENDS_BEFORE_STARTS 1543 +#define ER_EVENT_EXEC_TIME_IN_THE_PAST 1544 +#define ER_EVENT_OPEN_TABLE_FAILED 1545 +#define ER_EVENT_NEITHER_M_EXPR_NOR_M_AT 1546 +#define ER_COL_COUNT_DOESNT_MATCH_CORRUPTED 1547 +#define ER_CANNOT_LOAD_FROM_TABLE 1548 +#define ER_EVENT_CANNOT_DELETE 1549 +#define ER_EVENT_COMPILE_ERROR 1550 +#define ER_EVENT_SAME_NAME 1551 +#define ER_EVENT_DATA_TOO_LONG 1552 +#define ER_DROP_INDEX_FK 1553 +#define ER_WARN_DEPRECATED_SYNTAX_WITH_VER 1554 +#define ER_CANT_WRITE_LOCK_LOG_TABLE 1555 +#define ER_CANT_LOCK_LOG_TABLE 1556 +#define ER_FOREIGN_DUPLICATE_KEY 1557 +#define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE 1558 +#define ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR 1559 +#define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT 1560 +#define ER_NDB_CANT_SWITCH_BINLOG_FORMAT 1561 +#define ER_PARTITION_NO_TEMPORARY 1562 +#define ER_PARTITION_CONST_DOMAIN_ERROR 1563 +#define ER_PARTITION_FUNCTION_IS_NOT_ALLOWED 1564 +#define ER_DDL_LOG_ERROR 1565 +#define ER_NULL_IN_VALUES_LESS_THAN 1566 +#define ER_WRONG_PARTITION_NAME 1567 +#define ER_CANT_CHANGE_TX_ISOLATION 1568 +#define ER_DUP_ENTRY_AUTOINCREMENT_CASE 1569 +#define ER_EVENT_MODIFY_QUEUE_ERROR 1570 +#define ER_EVENT_SET_VAR_ERROR 1571 +#define ER_PARTITION_MERGE_ERROR 1572 +#define ER_CANT_ACTIVATE_LOG 1573 +#define ER_RBR_NOT_AVAILABLE 1574 +#define ER_BASE64_DECODE_ERROR 1575 +#define ER_EVENT_RECURSION_FORBIDDEN 1576 +#define ER_EVENTS_DB_ERROR 1577 +#define ER_ONLY_INTEGERS_ALLOWED 1578 +#define ER_UNSUPORTED_LOG_ENGINE 1579 +#define ER_BAD_LOG_STATEMENT 1580 +#define ER_CANT_RENAME_LOG_TABLE 1581 +#define ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT 1582 +#define ER_WRONG_PARAMETERS_TO_NATIVE_FCT 1583 +#define ER_WRONG_PARAMETERS_TO_STORED_FCT 1584 +#define ER_NATIVE_FCT_NAME_COLLISION 1585 +#define ER_DUP_ENTRY_WITH_KEY_NAME 1586 +#define ER_BINLOG_PURGE_EMFILE 1587 +#define ER_EVENT_CANNOT_CREATE_IN_THE_PAST 1588 +#define ER_EVENT_CANNOT_ALTER_IN_THE_PAST 1589 +#define ER_SLAVE_INCIDENT 1590 +#define ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT 1591 +#define ER_BINLOG_UNSAFE_STATEMENT 1592 +#define ER_SLAVE_FATAL_ERROR 1593 +#define ER_SLAVE_RELAY_LOG_READ_FAILURE 1594 +#define ER_SLAVE_RELAY_LOG_WRITE_FAILURE 1595 +#define ER_SLAVE_CREATE_EVENT_FAILURE 1596 +#define ER_SLAVE_MASTER_COM_FAILURE 1597 +#define ER_BINLOG_LOGGING_IMPOSSIBLE 1598 +#define ER_VIEW_NO_CREATION_CTX 1599 +#define ER_VIEW_INVALID_CREATION_CTX 1600 +#define ER_SR_INVALID_CREATION_CTX 1601 +#define ER_TRG_CORRUPTED_FILE 1602 +#define ER_TRG_NO_CREATION_CTX 1603 +#define ER_TRG_INVALID_CREATION_CTX 1604 +#define ER_EVENT_INVALID_CREATION_CTX 1605 +#define ER_TRG_CANT_OPEN_TABLE 1606 +#define ER_CANT_CREATE_SROUTINE 1607 +#define ER_SLAVE_AMBIGOUS_EXEC_MODE 1608 +#define ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT 1609 +#define ER_SLAVE_CORRUPT_EVENT 1610 +#define ER_LOAD_DATA_INVALID_COLUMN 1611 +#define ER_LOG_PURGE_NO_FILE 1612 +#define ER_NEED_REPREPARE 1613 +#define ER_DELAYED_NOT_SUPPORTED 1614 +#define ER_WARN_AUTO_CONVERT_LOCK 1615 +#define ER_NO_AUTO_CONVERT_LOCK_STRICT 1616 +#define ER_NO_AUTO_CONVERT_LOCK_TRANSACTION 1617 +#define ER_NO_STORAGE_ENGINE 1618 +#define ER_BACKUP_BACKUP_START 1619 +#define ER_BACKUP_BACKUP_DONE 1620 +#define ER_BACKUP_RESTORE_START 1621 +#define ER_BACKUP_RESTORE_DONE 1622 +#define ER_BACKUP_NOTHING_TO_BACKUP 1623 +#define ER_BACKUP_CANNOT_INCLUDE_DB 1624 +#define ER_BACKUP_BACKUP 1625 +#define ER_BACKUP_RESTORE 1626 +#define ER_BACKUP_RUNNING 1627 +#define ER_BACKUP_BACKUP_PREPARE 1628 +#define ER_BACKUP_RESTORE_PREPARE 1629 +#define ER_BACKUP_INVALID_LOC 1630 +#define ER_BACKUP_READ_LOC 1631 +#define ER_BACKUP_WRITE_LOC 1632 +#define ER_BACKUP_LIST_DBS 1633 +#define ER_BACKUP_LIST_TABLES 1634 +#define ER_BACKUP_LIST_DB_TABLES 1635 +#define ER_BACKUP_SKIP_VIEW 1636 +#define ER_BACKUP_NO_ENGINE 1637 +#define ER_BACKUP_TABLE_OPEN 1638 +#define ER_BACKUP_READ_HEADER 1639 +#define ER_BACKUP_WRITE_HEADER 1640 +#define ER_BACKUP_NO_BACKUP_DRIVER 1641 +#define ER_BACKUP_NOT_ACCEPTED 1642 +#define ER_BACKUP_CREATE_BACKUP_DRIVER 1643 +#define ER_BACKUP_CREATE_RESTORE_DRIVER 1644 +#define ER_BACKUP_TOO_MANY_IMAGES 1645 +#define ER_BACKUP_WRITE_META 1646 +#define ER_BACKUP_READ_META 1647 +#define ER_BACKUP_CREATE_META 1648 +#define ER_BACKUP_GET_BUF 1649 +#define ER_BACKUP_WRITE_DATA 1650 +#define ER_BACKUP_READ_DATA 1651 +#define ER_BACKUP_NEXT_CHUNK 1652 +#define ER_BACKUP_INIT_BACKUP_DRIVER 1653 +#define ER_BACKUP_INIT_RESTORE_DRIVER 1654 +#define ER_BACKUP_STOP_BACKUP_DRIVER 1655 +#define ER_BACKUP_STOP_RESTORE_DRIVERS 1656 +#define ER_BACKUP_PREPARE_DRIVER 1657 +#define ER_BACKUP_CREATE_VP 1658 +#define ER_BACKUP_UNLOCK_DRIVER 1659 +#define ER_BACKUP_CANCEL_BACKUP 1660 +#define ER_BACKUP_CANCEL_RESTORE 1661 +#define ER_BACKUP_GET_DATA 1662 +#define ER_BACKUP_SEND_DATA 1663 +#define ER_BACKUP_SEND_DATA_RETRY 1664 +#define ER_BACKUP_OPEN_TABLES 1665 +#define ER_BACKUP_THREAD_INIT 1666 +#define ER_BACKUP_PROGRESS_TABLES 1667 +#define ER_TABLESPACE_EXIST 1668 +#define ER_NO_SUCH_TABLESPACE 1669 +#define ER_SLAVE_HEARTBEAT_FAILURE 1670 +#define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE 1671 +#define ER_BACKUP_CANT_FIND_SE 1672 +#define ER_BACKUP_NO_NATIVE_BE 1673 +#define ER_BACKUP_UNKNOWN_BE 1674 +#define ER_BACKUP_WRONG_TABLE_BE 1675 +#define ER_BACKUP_CANT_RESTORE_DB 1676 +#define ER_BACKUP_CANT_RESTORE_TABLE 1677 +#define ER_BACKUP_CANT_RESTORE_VIEW 1678 +#define ER_BACKUP_CANT_RESTORE_SROUT 1679 +#define ER_BACKUP_CANT_RESTORE_EVENT 1680 +#define ER_BACKUP_CANT_RESTORE_TRIGGER 1681 +#define ER_BACKUP_CATALOG_ADD_DB 1682 +#define ER_BACKUP_CATALOG_ADD_TABLE 1683 +#define ER_BACKUP_CATALOG_ADD_VIEW 1684 +#define ER_BACKUP_CATALOG_ADD_SROUT 1685 +#define ER_BACKUP_CATALOG_ADD_EVENT 1686 +#define ER_BACKUP_CATALOG_ADD_TRIGGER 1687 +#define ER_BACKUP_UNKNOWN_OBJECT 1688 +#define ER_BACKUP_UNKNOWN_OBJECT_TYPE 1689 +#define ER_BACKUP_OPEN_WR 1690 +#define ER_BACKUP_OPEN_RD 1691 +#define ER_BACKUP_BAD_MAGIC 1692 +#define ER_BACKUP_CONTEXT_CREATE 1693 +#define ER_BACKUP_CONTEXT_REMOVE 1694 +#define ER_BAD_PATH 1695 +#define ER_DDL_BLOCK 1696 +#define ER_BACKUP_LOGGER_INIT 1697 +#define ER_BACKUP_WRITE_SUMMARY 1698 +#define ER_BACKUP_READ_SUMMARY 1699 +#define ER_BACKUP_GET_META_DB 1700 +#define ER_BACKUP_GET_META_TABLE 1701 +#define ER_BACKUP_GET_META_VIEW 1702 +#define ER_BACKUP_GET_META_SROUT 1703 +#define ER_BACKUP_GET_META_EVENT 1704 +#define ER_BACKUP_GET_META_TRIGGER 1705 +#define ER_BACKUP_CREATE_BE 1706 +#define ER_BACKUP_LIST_PERDB 1707 +#define ER_BACKUP_LIST_DB_VIEWS 1708 +#define ER_BACKUP_LIST_DB_SROUT 1709 +#define ER_BACKUP_LIST_DB_EVENTS 1710 +#define ER_BACKUP_LIST_DB_TRIGGERS 1711 +#define ER_BACKUP_LOG_WRITE_ERROR 1712 +#define ER_TABLESPACE_NOT_EMPTY 1713 +#define ER_BACKUP_CAT_ENUM 1714 +#define ER_BACKUP_CANT_RESTORE_TS 1715 +#define ER_BACKUP_TS_CHANGE 1716 +#define ER_BACKUP_GET_META_TS 1717 +#define ER_TABLESPACE_DATAFILE_EXIST 1718 +#define ER_BACKUP_CATALOG_ADD_TS 1719 +#define ER_DEBUG_SYNC_TIMEOUT 1720 +#define ER_DEBUG_SYNC_HIT_LIMIT 1721 +#define ER_BACKUP_FAILED_TO_INIT_COMPRESSION 1722 +#define ER_BACKUP_OBTAIN_NAME_LOCK_FAILED 1723 +#define ER_BACKUP_RELEASE_NAME_LOCK_FAILED 1724 +#define ER_BACKUP_BACKUPDIR 1725 +#define ER_ERROR_LAST 1725 diff --git a/mysql_incl/mysys/rijndael.h b/mysql_incl/mysys/rijndael.h new file mode 100644 index 0000000..89963a8 --- /dev/null +++ b/mysql_incl/mysys/rijndael.h @@ -0,0 +1,41 @@ +/* Copyright (C) 2002 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* + rijndael-alg-fst.h + + @version 3.0 (December 2000) + Optimised ANSI C code for the Rijndael cipher (now AES) + @author Vincent Rijmen + @author Antoon Bosselaers + @author Paulo Barreto + + This code is hereby placed in the public domain. + Modified by Peter Zaitsev to fit MySQL coding style. + */ + +#define AES_MAXKC (256/32) +#define AES_MAXKB (256/8) +#define AES_MAXNR 14 + +int rijndaelKeySetupEnc(uint32 rk[/*4*(Nr + 1)*/], const uint8 cipherKey[], + int keyBits); +int rijndaelKeySetupDec(uint32 rk[/*4*(Nr + 1)*/], const uint8 cipherKey[], + int keyBits); +void rijndaelEncrypt(const uint32 rk[/*4*(Nr + 1)*/], int Nr, + const uint8 pt[16], uint8 ct[16]); +void rijndaelDecrypt(const uint32 rk[/*4*(Nr + 1)*/], int Nr, + const uint8 ct[16], uint8 pt[16]); diff --git a/mysql_incl/mysys_err.h b/mysql_incl/mysys_err.h new file mode 100644 index 0000000..7167395 --- /dev/null +++ b/mysql_incl/mysys_err.h @@ -0,0 +1,90 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _mysys_err_h +#define _mysys_err_h +#ifdef __cplusplus +extern "C" { +#endif + +#define GLOBERRS (EE_ERROR_LAST - EE_ERROR_FIRST + 1) /* Nr of global errors */ +#define EE(X) (globerrs[(X) - EE_ERROR_FIRST]) + +extern const char * NEAR globerrs[]; /* my_error_messages is here */ + +/* Error message numbers in global map */ +/* + Do not add error numbers before EE_ERROR_FIRST. + If necessary to add lower numbers, change EE_ERROR_FIRST accordingly. + + We start with error 1 to not confuse peoples with 'error 0' +*/ + +#define EE_ERROR_FIRST 1 /*Copy first error nr.*/ +#define EE_CANTCREATEFILE 1 +#define EE_READ 2 +#define EE_WRITE 3 +#define EE_BADCLOSE 4 +#define EE_OUTOFMEMORY 5 +#define EE_DELETE 6 +#define EE_LINK 7 +#define EE_EOFERR 9 +#define EE_CANTLOCK 10 +#define EE_CANTUNLOCK 11 +#define EE_DIR 12 +#define EE_STAT 13 +#define EE_CANT_CHSIZE 14 +#define EE_CANT_OPEN_STREAM 15 +#define EE_GETWD 16 +#define EE_SETWD 17 +#define EE_LINK_WARNING 18 +#define EE_OPEN_WARNING 19 +#define EE_DISK_FULL 20 +#define EE_CANT_MKDIR 21 +#define EE_UNKNOWN_CHARSET 22 +#define EE_OUT_OF_FILERESOURCES 23 +#define EE_CANT_READLINK 24 +#define EE_CANT_SYMLINK 25 +#define EE_REALPATH 26 +#define EE_SYNC 27 +#define EE_UNKNOWN_COLLATION 28 +#define EE_FILENOTFOUND 29 +#define EE_FILE_NOT_CLOSED 30 +#define EE_CANT_CHMOD 31 +#define EE_ERROR_LAST 31 /* Copy last error nr */ +/* Add error numbers before EE_ERROR_LAST and change it accordingly. */ + + /* exit codes for all MySQL programs */ + +#define EXIT_UNSPECIFIED_ERROR 1 +#define EXIT_UNKNOWN_OPTION 2 +#define EXIT_AMBIGUOUS_OPTION 3 +#define EXIT_NO_ARGUMENT_ALLOWED 4 +#define EXIT_ARGUMENT_REQUIRED 5 +#define EXIT_VAR_PREFIX_NOT_UNIQUE 6 +#define EXIT_UNKNOWN_VARIABLE 7 +#define EXIT_OUT_OF_MEMORY 8 +#define EXIT_UNKNOWN_SUFFIX 9 +#define EXIT_NO_PTR_TO_VARIABLE 10 +#define EXIT_CANNOT_CONNECT_TO_SERVICE 11 +#define EXIT_OPTION_DISABLED 12 +#define EXIT_ARGUMENT_INVALID 13 + + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/mysql_incl/queues.h b/mysql_incl/queues.h new file mode 100644 index 0000000..d01b73b --- /dev/null +++ b/mysql_incl/queues.h @@ -0,0 +1,72 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Code for generell handling of priority Queues. + Implemention of queues from "Algoritms in C" by Robert Sedgewick. + Copyright Monty Program KB. + By monty. +*/ + +#ifndef _queues_h +#define _queues_h +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct st_queue { + uchar **root; + void *first_cmp_arg; + uint elements; + uint max_elements; + uint offset_to_key; /* compare is done on element+offset */ + int max_at_top; /* Normally 1, set to -1 if queue_top gives max */ + int (*compare)(void *, uchar *,uchar *); + uint auto_extent; +} QUEUE; + +#define queue_top(queue) ((queue)->root[1]) +#define queue_element(queue,index) ((queue)->root[index+1]) +#define queue_end(queue) ((queue)->root[(queue)->elements]) +#define queue_replaced(queue) _downheap(queue,1) +#define queue_set_cmp_arg(queue, set_arg) (queue)->first_cmp_arg= set_arg +#define queue_set_max_at_top(queue, set_arg) \ + (queue)->max_at_top= set_arg ? -1 : 1 +typedef int (*queue_compare)(void *,uchar *, uchar *); + +int init_queue(QUEUE *queue,uint max_elements,uint offset_to_key, + pbool max_at_top, queue_compare compare, + void *first_cmp_arg); +int init_queue_ex(QUEUE *queue,uint max_elements,uint offset_to_key, + pbool max_at_top, queue_compare compare, + void *first_cmp_arg, uint auto_extent); +int reinit_queue(QUEUE *queue,uint max_elements,uint offset_to_key, + pbool max_at_top, queue_compare compare, + void *first_cmp_arg); +int resize_queue(QUEUE *queue, uint max_elements); +void delete_queue(QUEUE *queue); +void queue_insert(QUEUE *queue,uchar *element); +int queue_insert_safe(QUEUE *queue, uchar *element); +uchar *queue_remove(QUEUE *queue,uint idx); +#define queue_remove_all(queue) { (queue)->elements= 0; } +#define queue_is_full(queue) (queue->elements == queue->max_elements) +void _downheap(QUEUE *queue,uint idx); +void queue_fix(QUEUE *queue); +#define is_queue_inited(queue) ((queue)->root != 0) + +#ifdef __cplusplus +} +#endif +#endif diff --git a/mysql_incl/sha1.h b/mysql_incl/sha1.h new file mode 100644 index 0000000..e476456 --- /dev/null +++ b/mysql_incl/sha1.h @@ -0,0 +1,66 @@ +/* Copyright (C) 2002, 2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + This is the header file for code which implements the Secure + Hashing Algorithm 1 as defined in FIPS PUB 180-1 published + April 17, 1995. + + Many of the variable names in this code, especially the + single character names, were used because those were the names + used in the publication. + + Please read the file sha1.c for more information. + + Modified 2002 by Peter Zaitsev to better follow MySQL standards +*/ + + +enum sha_result_codes +{ + SHA_SUCCESS = 0, + SHA_NULL, /* Null pointer parameter */ + SHA_INPUT_TOO_LONG, /* input data too long */ + SHA_STATE_ERROR /* called Input after Result */ +}; + +#define SHA1_HASH_SIZE 20 /* Hash size in bytes */ + +/* + This structure will hold context information for the SHA-1 + hashing operation +*/ + +typedef struct SHA1_CONTEXT +{ + ulonglong Length; /* Message length in bits */ + uint32 Intermediate_Hash[SHA1_HASH_SIZE/4]; /* Message Digest */ + int Computed; /* Is the digest computed? */ + int Corrupted; /* Is the message digest corrupted? */ + int16 Message_Block_Index; /* Index into message block array */ + uint8 Message_Block[64]; /* 512-bit message blocks */ +} SHA1_CONTEXT; + +/* + Function Prototypes +*/ + +C_MODE_START + +int mysql_sha1_reset(SHA1_CONTEXT*); +int mysql_sha1_input(SHA1_CONTEXT*, const uint8 *, unsigned int); +int mysql_sha1_result(SHA1_CONTEXT* , uint8 Message_Digest[SHA1_HASH_SIZE]); + +C_MODE_END diff --git a/mysql_incl/sha2.h b/mysql_incl/sha2.h new file mode 100644 index 0000000..49dbac5 --- /dev/null +++ b/mysql_incl/sha2.h @@ -0,0 +1,72 @@ +/* Copyright (C) 2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef included_sha2_h +#define included_sha2_h + +#include + +#if defined(HAVE_YASSL) || defined(HAVE_OPENSSL) + +# ifdef HAVE_STDDEF_H +# include +# endif + +# ifndef HAVE_YASSL +# include + +# else + +#include "../extra/yassl/taocrypt/include/sha.hpp" + +# ifdef __cplusplus +extern "C" { +# endif + +#ifndef SHA512_DIGEST_LENGTH +#define SHA512_DIGEST_LENGTH TaoCrypt::SHA512::DIGEST_SIZE +#endif + +#ifndef SHA384_DIGEST_LENGTH +#define SHA384_DIGEST_LENGTH TaoCrypt::SHA384::DIGEST_SIZE +#endif + +#ifndef SHA256_DIGEST_LENGTH +#define SHA256_DIGEST_LENGTH TaoCrypt::SHA256::DIGEST_SIZE +#endif + +#ifndef SHA224_DIGEST_LENGTH +#define SHA224_DIGEST_LENGTH TaoCrypt::SHA224::DIGEST_SIZE +#endif + +#define GEN_YASSL_SHA2_BRIDGE(size) \ +unsigned char* SHA##size(const unsigned char *input_ptr, size_t input_length, \ + char unsigned *output_ptr); + +GEN_YASSL_SHA2_BRIDGE(512); +GEN_YASSL_SHA2_BRIDGE(384); +GEN_YASSL_SHA2_BRIDGE(256); +GEN_YASSL_SHA2_BRIDGE(224); + +#undef GEN_YASSL_SHA2_BRIDGE + +# ifdef __cplusplus +} +# endif + +# endif /* HAVE_YASSL */ + +#endif /* HAVE_OPENSSL || HAVE_YASSL */ +#endif /* included_sha2_h */ diff --git a/mysql_incl/sql_common.h b/mysql_incl/sql_common.h new file mode 100644 index 0000000..9e43d07 --- /dev/null +++ b/mysql_incl/sql_common.h @@ -0,0 +1,50 @@ +/* Copyright (C) 2003-2004, 2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +extern const char *unknown_sqlstate; +extern const char *cant_connect_sqlstate; +extern const char *not_error_sqlstate; + +#ifdef __cplusplus +extern "C" { +#endif + +extern CHARSET_INFO *default_client_charset_info; +MYSQL_FIELD *unpack_fields(MYSQL_DATA *data,MEM_ROOT *alloc,uint fields, + my_bool default_value, uint server_capabilities); +void free_rows(MYSQL_DATA *cur); +void free_old_query(MYSQL *mysql); +void end_server(MYSQL *mysql); +my_bool mysql_reconnect(MYSQL *mysql); +void mysql_read_default_options(struct st_mysql_options *options, + const char *filename,const char *group); +my_bool +cli_advanced_command(MYSQL *mysql, enum enum_server_command command, + const unsigned char *header, ulong header_length, + const unsigned char *arg, ulong arg_length, + my_bool skip_check, MYSQL_STMT *stmt); +unsigned long cli_safe_read(MYSQL *mysql); +void net_clear_error(NET *net); +void set_stmt_errmsg(MYSQL_STMT *stmt, NET *net); +void set_stmt_error(MYSQL_STMT *stmt, int errcode, const char *sqlstate, + const char *err); +void set_mysql_error(MYSQL *mysql, int errcode, const char *sqlstate); +#ifdef __cplusplus +} +#endif + +#define protocol_41(A) ((A)->server_capabilities & CLIENT_PROTOCOL_41) + diff --git a/mysql_incl/sslopt-case.h b/mysql_incl/sslopt-case.h new file mode 100644 index 0000000..ee6c83c --- /dev/null +++ b/mysql_incl/sslopt-case.h @@ -0,0 +1,28 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) + case OPT_SSL_KEY: + case OPT_SSL_CERT: + case OPT_SSL_CA: + case OPT_SSL_CAPATH: + case OPT_SSL_CIPHER: + /* + Enable use of SSL if we are using any ssl option + One can disable SSL later by using --skip-ssl or --ssl=0 + */ + opt_use_ssl= 1; + break; +#endif diff --git a/mysql_incl/sslopt-vars.h b/mysql_incl/sslopt-vars.h new file mode 100644 index 0000000..9d25c33 --- /dev/null +++ b/mysql_incl/sslopt-vars.h @@ -0,0 +1,31 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) +#ifdef SSL_VARS_NOT_STATIC +#define SSL_STATIC +#else +#define SSL_STATIC static +#endif +SSL_STATIC my_bool opt_use_ssl = 0; +SSL_STATIC char *opt_ssl_ca = 0; +SSL_STATIC char *opt_ssl_capath = 0; +SSL_STATIC char *opt_ssl_cert = 0; +SSL_STATIC char *opt_ssl_cipher = 0; +SSL_STATIC char *opt_ssl_key = 0; +#ifdef MYSQL_CLIENT +SSL_STATIC my_bool opt_ssl_verify_server_cert= 0; +#endif +#endif diff --git a/mysql_incl/t_ctype.h b/mysql_incl/t_ctype.h new file mode 100644 index 0000000..1560001 --- /dev/null +++ b/mysql_incl/t_ctype.h @@ -0,0 +1,254 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Copyright (C) 1998, 1999 by Pruet Boonma, all rights reserved. + Copyright (C) 1998 by Theppitak Karoonboonyanan, all rights reserved. + Permission to use, copy, modify, distribute and sell this software + and its documentation for any purpose is hereby granted without fee, + provided that the above copyright notice appear in all copies. + Smaphan Raruenrom and Pruet Boonma makes no representations about + the suitability of this software for any purpose. It is provided + "as is" without express or implied warranty. +*/ + +/* LC_COLLATE category + Level information */ + +#ifndef _t_ctype_h +#define _t_ctype_h + +#define TOT_LEVELS 5 +#define LAST_LEVEL 4 /* TOT_LEVELS - 1 */ + +#define IGNORE 0 + + +/* level 1 symbols & order */ +enum l1_symbols { + L1_08 = TOT_LEVELS, + L1_18, + L1_28, + L1_38, + L1_48, + L1_58, + L1_68, + L1_78, + L1_88, + L1_98, + L1_A8, + L1_B8, + L1_C8, + L1_D8, + L1_E8, + L1_F8, + L1_G8, + L1_H8, + L1_I8, + L1_J8, + L1_K8, + L1_L8, + L1_M8, + L1_N8, + L1_O8, + L1_P8, + L1_Q8, + L1_R8, + L1_S8, + L1_T8, + L1_U8, + L1_V8, + L1_W8, + L1_X8, + L1_Y8, + L1_Z8, + L1_KO_KAI, + L1_KHO_KHAI, + L1_KHO_KHUAT, + L1_KHO_KHWAI, + L1_KHO_KHON, + L1_KHO_RAKHANG, + L1_NGO_NGU, + L1_CHO_CHAN, + L1_CHO_CHING, + L1_CHO_CHANG, + L1_SO_SO, + L1_CHO_CHOE, + L1_YO_YING, + L1_DO_CHADA, + L1_TO_PATAK, + L1_THO_THAN, + L1_THO_NANGMONTHO, + L1_THO_PHUTHAO, + L1_NO_NEN, + L1_DO_DEK, + L1_TO_TAO, + L1_THO_THUNG, + L1_THO_THAHAN, + L1_THO_THONG, + L1_NO_NU, + L1_BO_BAIMAI, + L1_PO_PLA, + L1_PHO_PHUNG, + L1_FO_FA, + L1_PHO_PHAN, + L1_FO_FAN, + L1_PHO_SAMPHAO, + L1_MO_MA, + L1_YO_YAK, + L1_RO_RUA, + L1_RU, + L1_LO_LING, + L1_LU, + L1_WO_WAEN, + L1_SO_SALA, + L1_SO_RUSI, + L1_SO_SUA, + L1_HO_HIP, + L1_LO_CHULA, + L1_O_ANG, + L1_HO_NOKHUK, + L1_NKHIT, + L1_SARA_A, + L1_MAI_HAN_AKAT, + L1_SARA_AA, + L1_SARA_AM, + L1_SARA_I, + L1_SARA_II, + L1_SARA_UE, + L1_SARA_UEE, + L1_SARA_U, + L1_SARA_UU, + L1_SARA_E, + L1_SARA_AE, + L1_SARA_O, + L1_SARA_AI_MAIMUAN, + L1_SARA_AI_MAIMALAI +}; + +/* level 2 symbols & order */ +enum l2_symbols { + L2_BLANK = TOT_LEVELS, + L2_THAII, + L2_YAMAK, + L2_PINTHU, + L2_GARAN, + L2_TYKHU, + L2_TONE1, + L2_TONE2, + L2_TONE3, + L2_TONE4 +}; + +/* level 3 symbols & order */ +enum l3_symbols { + L3_BLANK = TOT_LEVELS, + L3_SPACE, + L3_NB_SACE, + L3_LOW_LINE, + L3_HYPHEN, + L3_COMMA, + L3_SEMICOLON, + L3_COLON, + L3_EXCLAMATION, + L3_QUESTION, + L3_SOLIDUS, + L3_FULL_STOP, + L3_PAIYAN_NOI, + L3_MAI_YAMOK, + L3_GRAVE, + L3_CIRCUMFLEX, + L3_TILDE, + L3_APOSTROPHE, + L3_QUOTATION, + L3_L_PARANTHESIS, + L3_L_BRACKET, + L3_L_BRACE, + L3_R_BRACE, + L3_R_BRACKET, + L3_R_PARENTHESIS, + L3_AT, + L3_BAHT, + L3_DOLLAR, + L3_FONGMAN, + L3_ANGKHANKHU, + L3_KHOMUT, + L3_ASTERISK, + L3_BK_SOLIDUS, + L3_AMPERSAND, + L3_NUMBER, + L3_PERCENT, + L3_PLUS, + L3_LESS_THAN, + L3_EQUAL, + L3_GREATER_THAN, + L3_V_LINE +}; + +/* level 4 symbols & order */ +enum l4_symbols { + L4_BLANK = TOT_LEVELS, + L4_MIN, + L4_CAP, + L4_EXT +}; + +enum level_symbols { + L_UPRUPR = TOT_LEVELS, + L_UPPER, + L_MIDDLE, + L_LOWER +}; + +#define _is(c) (t_ctype[(c)][LAST_LEVEL]) +#define _level 8 +#define _consnt 16 +#define _ldvowel 32 +#define _fllwvowel 64 +#define _uprvowel 128 +#define _lwrvowel 256 +#define _tone 512 +#define _diacrt1 1024 +#define _diacrt2 2048 +#define _combine 4096 +#define _stone 8192 +#define _tdig 16384 +#define _rearvowel (_fllwvowel | _uprvowel | _lwrvowel) +#define _diacrt (_diacrt1 | _diacrt2) +#define levelof(c) ( _is(c) & _level ) +#define isthai(c) ( (c) >= 128 ) +#define istalpha(c) ( _is(c) & (_consnt|_ldvowel|_rearvowel|\ + _tone|_diacrt1|_diacrt2) ) +#define isconsnt(c) ( _is(c) & _consnt ) +#define isldvowel(c) ( _is(c) & _ldvowel ) +#define isfllwvowel(c) ( _is(c) & _fllwvowel ) +#define ismidvowel(c) ( _is(c) & (_ldvowel|_fllwvowel) ) +#define isuprvowel(c) ( _is(c) & _uprvowel ) +#define islwrvowel(c) ( _is(c) & _lwrvowel ) +#define isuprlwrvowel(c) ( _is(c) & (_lwrvowel | _uprvowel)) +#define isrearvowel(c) ( _is(c) & _rearvowel ) +#define isvowel(c) ( _is(c) & (_ldvowel|_rearvowel) ) +#define istone(c) ( _is(c) & _tone ) +#define isunldable(c) ( _is(c) & (_rearvowel|_tone|_diacrt1|_diacrt2) ) +#define iscombinable(c) ( _is(c) & _combine ) +#define istdigit(c) ( _is(c) & _tdig ) +#define isstone(c) ( _is(c) & _stone ) +#define isdiacrt1(c) ( _is(c) & _diacrt1) +#define isdiacrt2(c) ( _is(c) & _diacrt2) +#define isdiacrt(c) ( _is(c) & _diacrt) + +/* Function prototype called by sql/field.cc */ +void ThNormalize(uchar* ptr, uint field_length, const uchar* from, uint length); + +#endif diff --git a/mysql_incl/thr_alarm.h b/mysql_incl/thr_alarm.h new file mode 100644 index 0000000..fb90603 --- /dev/null +++ b/mysql_incl/thr_alarm.h @@ -0,0 +1,110 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* Prototypes when using thr_alarm library functions */ + +#ifndef _thr_alarm_h +#define _thr_alarm_h +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef USE_ALARM_THREAD +#define USE_ONE_SIGNAL_HAND /* One must call process_alarm */ +#endif +#ifdef HAVE_rts_threads +#undef USE_ONE_SIGNAL_HAND +#define USE_ALARM_THREAD +#define THR_SERVER_ALARM SIGUSR1 +#else +#define THR_SERVER_ALARM SIGALRM +#endif + +typedef struct st_alarm_info +{ + ulong next_alarm_time; + uint active_alarms; + uint max_used_alarms; +} ALARM_INFO; + +void thr_alarm_info(ALARM_INFO *info); + +#if defined(DONT_USE_THR_ALARM) || !defined(THREAD) + +#define USE_ALARM_THREAD +#undef USE_ONE_SIGNAL_HAND + +typedef my_bool thr_alarm_t; +typedef my_bool ALARM; + +#define thr_alarm_init(A) (*(A))=0 +#define thr_alarm_in_use(A) (*(A) != 0) +#define thr_end_alarm(A) +#define thr_alarm(A,B,C) ((*(A)=1)-1) +/* The following should maybe be (*(A)) */ +#define thr_got_alarm(A) 0 +#define init_thr_alarm(A) +#define thr_alarm_kill(A) +#define resize_thr_alarm(N) +#define end_thr_alarm(A) + +#else +#if defined(__WIN__) +typedef struct st_thr_alarm_entry +{ + rf_SetTimer crono; +} thr_alarm_entry; + +#else /* System with posix threads */ + +typedef int thr_alarm_entry; + +#define thr_got_alarm(thr_alarm) (**(thr_alarm)) + +#endif /* __WIN__ */ + +typedef thr_alarm_entry* thr_alarm_t; + +typedef struct st_alarm { + ulong expire_time; + thr_alarm_entry alarmed; /* set when alarm is due */ + pthread_t thread; + my_thread_id thread_id; + my_bool malloced; +} ALARM; + +extern uint thr_client_alarm; +extern pthread_t alarm_thread; + +#define thr_alarm_init(A) (*(A))=0 +#define thr_alarm_in_use(A) (*(A)!= 0) +void init_thr_alarm(uint max_alarm); +void resize_thr_alarm(uint max_alarms); +my_bool thr_alarm(thr_alarm_t *alarmed, uint sec, ALARM *buff); +void thr_alarm_kill(my_thread_id thread_id); +void thr_end_alarm(thr_alarm_t *alarmed); +void end_thr_alarm(my_bool free_structures); +sig_handler process_alarm(int); +#ifndef thr_got_alarm +my_bool thr_got_alarm(thr_alarm_t *alrm); +#endif + + +#endif /* DONT_USE_THR_ALARM */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* _thr_alarm_h */ diff --git a/mysql_incl/thr_lock.h b/mysql_incl/thr_lock.h new file mode 100644 index 0000000..38f0478 --- /dev/null +++ b/mysql_incl/thr_lock.h @@ -0,0 +1,181 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* For use with thr_lock:s */ + +#ifndef _thr_lock_h +#define _thr_lock_h +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +struct st_thr_lock; +extern ulong locks_immediate,locks_waited ; + +/** + Lock types are used to request a lock on a table. Changes in this enumeration + might affect transactional locks as well. + Important: if a new lock type is added, a matching lock description + must be added to sql_test.cc's lock_descriptions array. + @see set_handler_table_locks + @see read_lock_type_for_table +*/ +enum thr_lock_type { TL_IGNORE=-1, + TL_UNLOCK, /* UNLOCK ANY LOCK */ + /* + Parser only! At open_tables() becomes TL_READ or + TL_READ_NO_INSERT depending on the binary log format + (SBR/RBR) and on the table category (log table). + Used for tables that are read by statements which + modify tables. + */ + TL_READ_DEFAULT, + TL_READ, /* Read lock */ + TL_READ_WITH_SHARED_LOCKS, + /* High prior. than TL_WRITE. Allow concurrent insert */ + TL_READ_HIGH_PRIORITY, + /* READ, Don't allow concurrent insert */ + TL_READ_NO_INSERT, + /* + Write lock, but allow other threads to read / write. + Used by BDB tables in MySQL to mark that someone is + reading/writing to the table. + */ + TL_WRITE_ALLOW_WRITE, + /* + Write lock, but allow other threads to read. + Used by ALTER TABLE in MySQL to allow readers + to use the table until ALTER TABLE is finished. + */ + TL_WRITE_ALLOW_READ, + /* + WRITE lock used by concurrent insert. Will allow + READ, if one could use concurrent insert on table. + */ + TL_WRITE_CONCURRENT_INSERT, + /* Write used by INSERT DELAYED. Allows READ locks */ + TL_WRITE_DELAYED, + /* + parser only! Late bound low_priority flag. + At open_tables() becomes thd->update_lock_default. + */ + TL_WRITE_DEFAULT, + /* WRITE lock that has lower priority than TL_READ */ + TL_WRITE_LOW_PRIORITY, + /* Normal WRITE lock */ + TL_WRITE, + /* Abort new lock request with an error */ + TL_WRITE_ONLY}; + +enum enum_thr_lock_result { THR_LOCK_SUCCESS= 0, THR_LOCK_ABORTED= 1, + THR_LOCK_WAIT_TIMEOUT= 2, THR_LOCK_DEADLOCK= 3 }; + + +extern ulong max_write_lock_count; +extern ulong table_lock_wait_timeout; +extern my_bool thr_lock_inited; +extern enum thr_lock_type thr_upgraded_concurrent_insert_lock; + +/* + A description of the thread which owns the lock. The address + of an instance of this structure is used to uniquely identify the thread. +*/ + +typedef struct st_thr_lock_info +{ + pthread_t thread; + my_thread_id thread_id; + ulong n_cursors; +} THR_LOCK_INFO; + +/* + Lock owner identifier. Globally identifies the lock owner within the + thread and among all the threads. The address of an instance of this + structure is used as id. +*/ + +typedef struct st_thr_lock_owner +{ + THR_LOCK_INFO *info; +} THR_LOCK_OWNER; + + +typedef struct st_thr_lock_data { + THR_LOCK_OWNER *owner; + struct st_thr_lock_data *next,**prev; + struct st_thr_lock *lock; + pthread_cond_t *cond; + enum thr_lock_type type; + void *status_param; /* Param to status functions */ + void *debug_print_param; +} THR_LOCK_DATA; + +struct st_lock_list { + THR_LOCK_DATA *data,**last; +}; + +typedef struct st_thr_lock { + LIST list; + pthread_mutex_t mutex; + struct st_lock_list read_wait; + struct st_lock_list read; + struct st_lock_list write_wait; + struct st_lock_list write; + /* write_lock_count is incremented for write locks and reset on read locks */ + ulong write_lock_count; + uint read_no_write_count; + void (*get_status)(void*, my_bool); /* When one gets a lock */ + void (*copy_status)(void*,void*); + void (*update_status)(void*); /* Before release of write */ + void (*restore_status)(void*); /* Before release of read */ + my_bool (*check_status)(void *); + my_bool allow_multiple_concurrent_insert; +} THR_LOCK; + + +extern LIST *thr_lock_thread_list; +extern pthread_mutex_t THR_LOCK_lock; + +my_bool init_thr_lock(void); /* Must be called once/thread */ +#define thr_lock_owner_init(owner, info_arg) (owner)->info= (info_arg) +void thr_lock_info_init(THR_LOCK_INFO *info); +void thr_lock_init(THR_LOCK *lock); +void thr_lock_delete(THR_LOCK *lock); +void thr_lock_data_init(THR_LOCK *lock,THR_LOCK_DATA *data, + void *status_param); +enum enum_thr_lock_result thr_lock(THR_LOCK_DATA *data, + THR_LOCK_OWNER *owner, + enum thr_lock_type lock_type); +void thr_unlock(THR_LOCK_DATA *data); +enum enum_thr_lock_result thr_multi_lock(THR_LOCK_DATA **data, + uint count, THR_LOCK_OWNER *owner); +void thr_multi_unlock(THR_LOCK_DATA **data,uint count); +void +thr_lock_merge_status(THR_LOCK_DATA **data, uint count); +void thr_abort_locks(THR_LOCK *lock, my_bool upgrade_lock); +my_bool thr_abort_locks_for_thread(THR_LOCK *lock, my_thread_id thread); +void thr_print_locks(void); /* For debugging */ +my_bool thr_upgrade_write_delay_lock(THR_LOCK_DATA *data, + enum thr_lock_type new_lock_type); +void thr_downgrade_write_lock(THR_LOCK_DATA *data, + enum thr_lock_type new_lock_type); +my_bool thr_reschedule_write_lock(THR_LOCK_DATA *data); +#ifdef __cplusplus +} +#endif +#endif /* _thr_lock_h */ diff --git a/mysql_incl/typelib.h b/mysql_incl/typelib.h new file mode 100644 index 0000000..46106d1 --- /dev/null +++ b/mysql_incl/typelib.h @@ -0,0 +1,39 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +#ifndef _typelib_h +#define _typelib_h + +#include "my_alloc.h" + +typedef struct st_typelib { /* Different types saved here */ + unsigned int count; /* How many types */ + const char *name; /* Name of typelib */ + const char **type_names; + unsigned int *type_lengths; +} TYPELIB; + +extern my_ulonglong find_typeset(char *x, TYPELIB *typelib,int *error_position); +extern int find_type_or_exit(const char *x, TYPELIB *typelib, + const char *option); +extern int find_type(char *x, const TYPELIB *typelib, unsigned int full_name); +extern void make_type(char *to,unsigned int nr,TYPELIB *typelib); +extern const char *get_type(TYPELIB *typelib,unsigned int nr); +extern TYPELIB *copy_typelib(MEM_ROOT *root, TYPELIB *from); + +extern TYPELIB sql_protocol_typelib; + +#endif /* _typelib_h */ diff --git a/mysql_incl/violite.h b/mysql_incl/violite.h new file mode 100644 index 0000000..2720047 --- /dev/null +++ b/mysql_incl/violite.h @@ -0,0 +1,222 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + * Vio Lite. + * Purpose: include file for Vio that will work with C and C++ + */ + +#ifndef vio_violite_h_ +#define vio_violite_h_ + +#include "my_net.h" /* needed because of struct in_addr */ + + +/* Simple vio interface in C; The functions are implemented in violite.c */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +enum enum_vio_type +{ + VIO_CLOSED, VIO_TYPE_TCPIP, VIO_TYPE_SOCKET, VIO_TYPE_NAMEDPIPE, + VIO_TYPE_SSL, VIO_TYPE_SHARED_MEMORY +}; + + +#define VIO_LOCALHOST 1 /* a localhost connection */ +#define VIO_BUFFERED_READ 2 /* use buffered read */ +#define VIO_READ_BUFFER_SIZE 16384 /* size of read buffer */ + +Vio* vio_new(my_socket sd, enum enum_vio_type type, uint flags); +#ifdef __WIN__ +Vio* vio_new_win32pipe(HANDLE hPipe); +Vio* vio_new_win32shared_memory(NET *net,HANDLE handle_file_map, + HANDLE handle_map, + HANDLE event_server_wrote, + HANDLE event_server_read, + HANDLE event_client_wrote, + HANDLE event_client_read, + HANDLE event_conn_closed); +size_t vio_read_pipe(Vio *vio, uchar * buf, size_t size); +size_t vio_write_pipe(Vio *vio, const uchar * buf, size_t size); +int vio_close_pipe(Vio * vio); +#else +#define HANDLE void * +#endif /* __WIN__ */ + +void vio_delete(Vio* vio); +int vio_close(Vio* vio); +void vio_reset(Vio* vio, enum enum_vio_type type, + my_socket sd, HANDLE hPipe, uint flags); +size_t vio_read(Vio *vio, uchar * buf, size_t size); +size_t vio_read_buff(Vio *vio, uchar * buf, size_t size); +size_t vio_write(Vio *vio, const uchar * buf, size_t size); +int vio_blocking(Vio *vio, my_bool onoff, my_bool *old_mode); +my_bool vio_is_blocking(Vio *vio); +/* setsockopt TCP_NODELAY at IPPROTO_TCP level, when possible */ +int vio_fastsend(Vio *vio); +/* setsockopt SO_KEEPALIVE at SOL_SOCKET level, when possible */ +int vio_keepalive(Vio *vio, my_bool onoff); +/* Whenever we should retry the last read/write operation. */ +my_bool vio_should_retry(Vio *vio); +/* Check that operation was timed out */ +my_bool vio_was_interrupted(Vio *vio); +/* Short text description of the socket for those, who are curious.. */ +const char* vio_description(Vio *vio); +/* Return the type of the connection */ +enum enum_vio_type vio_type(Vio* vio); +/* Return last error number */ +int vio_errno(Vio*vio); +/* Get socket number */ +my_socket vio_fd(Vio*vio); +/* Remote peer's address and name in text form */ +my_bool vio_peer_addr(Vio *vio, char *buf, uint16 *port, size_t buflen); +my_bool vio_poll_read(Vio *vio,uint timeout); +my_bool vio_peek_read(Vio *vio, uint *bytes); +ssize_t vio_pending(Vio *vio); + +#ifdef HAVE_OPENSSL +#include +#if OPENSSL_VERSION_NUMBER < 0x0090700f +#define DES_cblock des_cblock +#define DES_key_schedule des_key_schedule +#define DES_set_key_unchecked(k,ks) des_set_key_unchecked((k),*(ks)) +#define DES_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e) des_ede3_cbc_encrypt((i),(o),(l),*(k1),*(k2),*(k3),(iv),(e)) +#endif + +#define HEADER_DES_LOCL_H dummy_something +#define YASSL_MYSQL_COMPATIBLE +#ifndef YASSL_PREFIX +#define YASSL_PREFIX +#endif +/* Set yaSSL to use same type as MySQL do for socket handles */ +typedef my_socket YASSL_SOCKET_T; +#define YASSL_SOCKET_T_DEFINED +#include +#include + +#ifndef EMBEDDED_LIBRARY + +struct st_VioSSLFd +{ + SSL_CTX *ssl_context; +}; + +int sslaccept(struct st_VioSSLFd*, Vio *, long timeout); +int sslconnect(struct st_VioSSLFd*, Vio *, long timeout); + +struct st_VioSSLFd +*new_VioSSLConnectorFd(const char *key_file, const char *cert_file, + const char *ca_file, const char *ca_path, + const char *cipher); +struct st_VioSSLFd +*new_VioSSLAcceptorFd(const char *key_file, const char *cert_file, + const char *ca_file,const char *ca_path, + const char *cipher); +void free_vio_ssl_acceptor_fd(struct st_VioSSLFd *fd); +#endif /* ! EMBEDDED_LIBRARY */ +#endif /* HAVE_OPENSSL */ + +#ifdef HAVE_SMEM +size_t vio_read_shared_memory(Vio *vio, uchar * buf, size_t size); +size_t vio_write_shared_memory(Vio *vio, const uchar * buf, size_t size); +int vio_close_shared_memory(Vio * vio); +#endif + +void vio_end(void); + +#ifdef __cplusplus +} +#endif + +#if !defined(DONT_MAP_VIO) +#define vio_delete(vio) (vio)->viodelete(vio) +#define vio_errno(vio) (vio)->vioerrno(vio) +#define vio_read(vio, buf, size) ((vio)->read)(vio,buf,size) +#define vio_write(vio, buf, size) ((vio)->write)(vio, buf, size) +#define vio_blocking(vio, set_blocking_mode, old_mode)\ + (vio)->vioblocking(vio, set_blocking_mode, old_mode) +#define vio_is_blocking(vio) (vio)->is_blocking(vio) +#define vio_fastsend(vio) (vio)->fastsend(vio) +#define vio_keepalive(vio, set_keep_alive) (vio)->viokeepalive(vio, set_keep_alive) +#define vio_should_retry(vio) (vio)->should_retry(vio) +#define vio_was_interrupted(vio) (vio)->was_interrupted(vio) +#define vio_close(vio) ((vio)->vioclose)(vio) +#define vio_peer_addr(vio, buf, prt, buflen) (vio)->peer_addr(vio, buf, prt, buflen) +#define vio_timeout(vio, which, seconds) (vio)->timeout(vio, which, seconds) +#endif /* !defined(DONT_MAP_VIO) */ + +/* This enumerator is used in parser - should be always visible */ +enum SSL_type +{ + SSL_TYPE_NOT_SPECIFIED= -1, + SSL_TYPE_NONE, + SSL_TYPE_ANY, + SSL_TYPE_X509, + SSL_TYPE_SPECIFIED +}; + + +/* HFTODO - hide this if we don't want client in embedded server */ +/* This structure is for every connection on both sides */ +struct st_vio +{ + my_socket sd; /* my_socket - real or imaginary */ + HANDLE hPipe; + my_bool localhost; /* Are we from localhost? */ + int fcntl_mode; /* Buffered fcntl(sd,F_GETFL) */ + struct sockaddr_storage local; /* Local internet address */ + struct sockaddr_storage remote; /* Remote internet address */ + int addrLen; /* Length of remote address */ + enum enum_vio_type type; /* Type of connection */ + char desc[30]; /* String description */ + char *read_buffer; /* buffer for vio_read_buff */ + char *read_pos; /* start of unfetched data in the + read buffer */ + char *read_end; /* end of unfetched data */ + /* function pointers. They are similar for socket/SSL/whatever */ + void (*viodelete)(Vio*); + int (*vioerrno)(Vio*); + size_t (*read)(Vio*, uchar *, size_t); + size_t (*write)(Vio*, const uchar *, size_t); + int (*vioblocking)(Vio*, my_bool, my_bool *); + my_bool (*is_blocking)(Vio*); + int (*viokeepalive)(Vio*, my_bool); + int (*fastsend)(Vio*); + my_bool (*peer_addr)(Vio*, char *, uint16*, size_t); + void (*in_addr)(Vio*, struct sockaddr_storage*); + my_bool (*should_retry)(Vio*); + my_bool (*was_interrupted)(Vio*); + int (*vioclose)(Vio*); + void (*timeout)(Vio*, unsigned int which, unsigned int timeout); +#ifdef HAVE_OPENSSL + void *ssl_arg; +#endif +#ifdef HAVE_SMEM + HANDLE handle_file_map; + char *handle_map; + HANDLE event_server_wrote; + HANDLE event_server_read; + HANDLE event_client_wrote; + HANDLE event_client_read; + HANDLE event_conn_closed; + size_t shared_memory_remain; + char *shared_memory_pos; + NET *net; +#endif /* HAVE_SMEM */ +}; +#endif /* vio_violite_h_ */ diff --git a/mysql_incl/waiting_threads.h b/mysql_incl/waiting_threads.h new file mode 100644 index 0000000..1e58052 --- /dev/null +++ b/mysql_incl/waiting_threads.h @@ -0,0 +1,130 @@ +/* Copyright (C) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _waiting_threads_h +#define _waiting_threads_h + +#include +#include + +#include + +C_MODE_START + +typedef struct st_wt_resource_id WT_RESOURCE_ID; +typedef struct st_wt_resource WT_RESOURCE; + +typedef struct st_wt_resource_type { + my_bool (*compare)(const void *a, const void *b); + const void *(*make_key)(const WT_RESOURCE_ID *id, uint *len); /* not used */ +} WT_RESOURCE_TYPE; + +struct st_wt_resource_id { + ulonglong value; + const WT_RESOURCE_TYPE *type; +}; +/* the below differs from sizeof(WT_RESOURCE_ID) by the amount of padding */ +#define sizeof_WT_RESOURCE_ID (sizeof(ulonglong)+sizeof(void*)) + +#define WT_WAIT_STATS 24 +#define WT_CYCLE_STATS 32 +extern ulonglong wt_wait_table[WT_WAIT_STATS]; +extern uint32 wt_wait_stats[WT_WAIT_STATS+1]; +extern uint32 wt_cycle_stats[2][WT_CYCLE_STATS+1]; +extern uint32 wt_success_stats; + +typedef struct st_wt_thd { + /* + XXX + there's no protection (mutex) against concurrent access of the + dynarray below. it is assumed that a caller will have it anyway + (not to protect this array but to protect its own - caller's - + data structures), and we'll get it for free. A caller needs to + ensure that a blocker won't release a resource before a blocked + thread starts waiting, which is usually done with a mutex. + + If the above assumption is wrong, we'll need to add a mutex here. + */ + DYNAMIC_ARRAY my_resources; + /* + 'waiting_for' is modified under waiting_for->lock, and only by thd itself + 'waiting_for' is read lock-free (using pinning protocol), but a thd object + can read its own 'waiting_for' without any locks or tricks. + */ + WT_RESOURCE *waiting_for; + LF_PINS *pins; + + /* pointers to values */ + const ulong *timeout_short; + const ulong *deadlock_search_depth_short; + const ulong *timeout_long; + const ulong *deadlock_search_depth_long; + + /* + weight relates to the desirability of a transaction being killed if it's + part of a deadlock. In a deadlock situation transactions with lower weights + are killed first. + + Examples of using the weight to implement different selection strategies: + + 1. Latest + Keep all weights equal. + 2. Random + Assight weights at random. + (variant: modify a weight randomly before every lock request) + 3. Youngest + Set weight to -NOW() + 4. Minimum locks + count locks granted in your lock manager, store the value as a weight + 5. Minimum work + depends on the definition of "work". For example, store the number + of rows modifies in this transaction (or a length of REDO log for a + transaction) as a weight. + + It is only statistically relevant and is not protected by any locks. + */ + ulong volatile weight; + /* + 'killed' is indirectly protected by waiting_for->lock because + a killed thread needs to clear its 'waiting_for' and thus needs a lock. + That is a thread needs an exclusive lock to read 'killed' reliably. + But other threads may change 'killed' from 0 to 1, a shared + lock is enough for that. + */ + my_bool killed; +#ifndef DBUG_OFF + const char *name; +#endif +} WT_THD; + +#define WT_TIMEOUT ETIMEDOUT +#define WT_OK 0 +#define WT_DEADLOCK -1 +#define WT_DEPTH_EXCEEDED -2 +#define WT_FREE_TO_GO -3 + +void wt_init(void); +void wt_end(void); +void wt_thd_lazy_init(WT_THD *, const ulong *, const ulong *, const ulong *, const ulong *); +void wt_thd_destroy(WT_THD *); +int wt_thd_will_wait_for(WT_THD *, WT_THD *, const WT_RESOURCE_ID *); +int wt_thd_cond_timedwait(WT_THD *, pthread_mutex_t *); +void wt_thd_release(WT_THD *, const WT_RESOURCE_ID *); +#define wt_thd_release_all(THD) wt_thd_release((THD), 0) +my_bool wt_resource_id_memcmp(const void *, const void *); + +C_MODE_END + +#endif diff --git a/mysql_incl/wqueue.h b/mysql_incl/wqueue.h new file mode 100644 index 0000000..658f3d6 --- /dev/null +++ b/mysql_incl/wqueue.h @@ -0,0 +1,27 @@ + +#ifndef _wqueue_h +#define _wqueue_h + +#include +#include + +/* info about requests in a waiting queue */ +typedef struct st_pagecache_wqueue +{ + struct st_my_thread_var *last_thread; /* circular list of waiting + threads */ +} WQUEUE; + +#ifdef THREAD +void wqueue_link_into_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); +void wqueue_unlink_from_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); +void wqueue_add_to_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); +void wqueue_add_and_wait(WQUEUE *wqueue, + struct st_my_thread_var *thread, + pthread_mutex_t *lock); +void wqueue_release_queue(WQUEUE *wqueue); +void wqueue_release_one_locktype_from_queue(WQUEUE *wqueue); + +#endif + +#endif diff --git a/proceso_cliente.cpp b/proceso_cliente.cpp new file mode 100644 index 0000000..2733e29 --- /dev/null +++ b/proceso_cliente.cpp @@ -0,0 +1,18 @@ +#include "StdAfx.h" +#include "proceso_cliente.h" +#include "sock_sv.h" +//********************************************************************** +Cproceso_cliente::Cproceso_cliente(void) +{ + soc=NULL; +} +//********************************************************************** +Cproceso_cliente::~Cproceso_cliente(void) +{ + if(soc) + { + soc->Close(); + delete soc; + } +} +//********************************************************************** diff --git a/proceso_cliente.h b/proceso_cliente.h new file mode 100644 index 0000000..d1cb232 --- /dev/null +++ b/proceso_cliente.h @@ -0,0 +1,12 @@ +#pragma once +#include "_proceso.h" +#include "base_head.h" +class Csock_sv; +class UTILES_EXPORT Cproceso_cliente: public C_proceso +{ +public: + Csock_sv *soc; + Cproceso_cliente(void); + ~Cproceso_cliente(void); + //virtual void run(){}; +}; diff --git a/puerto_com.cpp b/puerto_com.cpp new file mode 100644 index 0000000..5c80818 --- /dev/null +++ b/puerto_com.cpp @@ -0,0 +1,205 @@ +#include "StdAfx.h" +#include "_error.h" +#include "puerto_com.h" +//************************************************************************************************************ +Cpuerto_com::Cpuerto_com(C_error *err/*=NULL*/ ) +{ + if (err) + { + borra_error=FALSE; + er=err; + } + else + { + borra_error=TRUE; + er=new C_error(); + } + hport=INVALID_HANDLE_VALUE; +} +//************************************************************************************************************ +Cpuerto_com::~Cpuerto_com(void) +{ + if (er&&borra_error) + delete er; +} +//************************************************************************************************************ +BOOL Cpuerto_com::inicia( Puerto_com_conf* conf ) +{ + DCB m_dcb; + COMMTIMEOUTS m_CommTimeouts; + //creamos------------------------------------------- + hport=CreateFile(conf->com, + GENERIC_READ | GENERIC_WRITE, + 0, // exclusive access + NULL, // no security + OPEN_EXISTING, + 0, // no overlapped I/O + NULL); // null template + + if (hport == INVALID_HANDLE_VALUE) + { + er->pon_win(MODULO_CPUERTO_COM); + return FALSE; + } + //configuramos sizes------------------------------- + if(!SetupComm(hport, 128, 128)) + { + er->pon_win(MODULO_CPUERTO_COM); + goto salir; + } + //configuramos------------------------------------- + if(!GetCommState(hport, &m_dcb)) + { + er->pon_win(MODULO_CPUERTO_COM); + goto salir; + } + m_dcb.BaudRate = conf->baud; + m_dcb.ByteSize = conf->nb; + m_dcb.Parity = conf->paridad; + m_dcb.StopBits = conf->b_parada; +/* m_dcb.fRtsControl*/ + if(!SetCommState(hport, &m_dcb)) + { + er->pon_win(MODULO_CPUERTO_COM); + goto salir; + } + //configuracion de timeours------------------------ + if(!GetCommTimeouts(hport, &m_CommTimeouts)) + { + er->pon_win(MODULO_CPUERTO_COM); + goto salir; + } + //valores por defecto------------------------------ + m_CommTimeouts.ReadIntervalTimeout = 50; + m_CommTimeouts.ReadTotalTimeoutConstant = 50; + m_CommTimeouts.ReadTotalTimeoutMultiplier = 10; + m_CommTimeouts.WriteTotalTimeoutConstant = 50; + m_CommTimeouts.WriteTotalTimeoutMultiplier = 10; + if(!SetCommTimeouts(hport, &m_CommTimeouts)) + { + er->pon_win(MODULO_CPUERTO_COM); + goto salir; + } + return TRUE; + +salir: + termina(); + return FALSE; +} +//************************************************************************************************************ +void Cpuerto_com::termina() +{ + if (hport!=INVALID_HANDLE_VALUE) + CloseHandle(hport); + hport=INVALID_HANDLE_VALUE; +} +//************************************************************************************************************ +BOOL Cpuerto_com::escribe( BYTE* b,int nb ) +{ + DWORD iBytesWritten; + DWORD dwError=0; + int i=0; + COMSTAT cst; + int v=0; + while(TRUE) + { + if(!WriteFile(hport, &b[i], nb-i, &iBytesWritten, NULL)) + { + er->pon_win(MODULO_CPUERTO_COM); + ClearCommError(hport,&dwError,&cst); + return FALSE; + } + i+=iBytesWritten; + if(i>=nb) + break; + if(!iBytesWritten) + { + v++; + if(v>10) + { + er->pon(MODULO_CPUERTO_COM,"Demasiado tiempo en espera para escribir datos",-1); + return FALSE; + } + Sleep(1); + } + } + +/* + if (!rs || iBytesWritten == 0) + { + papp->wgeolog(LOG_POCO, "modem", "Error al pedir el tamaño: deseados=%ld," + "Escritos=%d, Error=%d",num_bytes,iBytesWritten, dwError); + return(-1); + }*/ + return TRUE; +} +//************************************************************************************************************ +int Cpuerto_com::lee( int nb ) +{ + BOOL rs; + DWORD iBytesRead=-1,dw; + COMSTAT cst; + if (nb>1023) + nb=1023; + memset(buf,0,1024); + rs = ReadFile(hport, (LPSTR) buf, nb, &iBytesRead, NULL); + if (!rs) + { + er->pon_win(MODULO_CPUERTO_COM); + ClearCommError(hport,&dw,&cst); + } + return iBytesRead; +} +//************************************************************************************************************ +int Cpuerto_com::lee( int nb, int ms, int veces) +{ + BOOL rs; + DWORD iBytesRead=-1,dw; + COMSTAT cst; + int i=0, rep=0; + if (nb>1023) + nb=1023; + memset(buf,0,1024); + while(TRUE) + { + rs = ReadFile(hport, (LPSTR) &buf[i], nb-i, &iBytesRead, NULL); + if(!rs) + break; + i+=iBytesRead; + if(i>=nb) + break; + if(iBytesRead<=0) + { + rep++; + if (rep>veces) + { + er->pon(MODULO_CPUERTO_COM,"Demasiado tiempo en espera para leer datos",-1); + break; + } + } + else + rep=0; + Sleep(ms); + + } + //rs = ReadFile(hport, (LPSTR) buf, nb, &iBytesRead, NULL); + if (!rs) + { + er->pon_win(MODULO_CPUERTO_COM); + ClearCommError(hport,&dw,&cst); + } + return i; +} +//************************************************************************************************************ + +int Cpuerto_com::escribeylee( BYTE* b,int nb, int time_sleep ) +{ + if(!escribe(b,nb)) + return -1; + Sleep(time_sleep); + if(lee(nb)<0) + return -1; + return lee(); +} +//************************************************************************************************************ + diff --git a/puerto_com.h b/puerto_com.h new file mode 100644 index 0000000..4a9e3b1 --- /dev/null +++ b/puerto_com.h @@ -0,0 +1,34 @@ +#pragma once +#include "base_head.h" + +#define MODULO_CPUERTO_COM "Cpuerto_com" +typedef struct Puerto_com_conf//configuracion del puerto com +{ + char com[10]; //puerto EJEM:"\\\\.\\COM1" + int baud; //velocidad( baudrate) desde CBR_110 hasta CBR_256000 + int nb; //numero de bytes (normalmente 8) + int paridad; //normalmente NOPARITY + int b_parada; //(normalmente ONESTOPBIT) +}Puerto_com_conf; + +class C_error; +class UTILES_EXPORT Cpuerto_com +{ +public: + //variables--------------------------------------------- + C_error *er; + BYTE* buf[1024]; +private: + BOOL borra_error; + HANDLE hport; +public: + Cpuerto_com(C_error *err=NULL); + ~Cpuerto_com(void); + //funciones--------------------------------------------- + BOOL inicia(Puerto_com_conf* conf ); + BOOL escribe(BYTE* b,int nb); + int lee(int nb=512);//recibe nb bytes (1024 maximo (total del buf)) + int lee( int nb, int ms, int veces=10);//recive nb bytes insiste veces con esperas de ms + int escribeylee(BYTE* b,int nb, int time_sleep); + void termina(); +}; diff --git a/res/utiles.rc2 b/res/utiles.rc2 new file mode 100644 index 0000000..fe388d4 --- /dev/null +++ b/res/utiles.rc2 @@ -0,0 +1,13 @@ +// +// utiles.RC2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED +#error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... + +///////////////////////////////////////////////////////////////////////////// diff --git a/resource.h b/resource.h new file mode 100644 index 0000000..94cf59d --- /dev/null +++ b/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by utiles.rc +// +#define IDP_SOCKETS_INIT_FAILED 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 1001 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 1000 +#endif +#endif diff --git a/sock_http.cpp b/sock_http.cpp new file mode 100644 index 0000000..0c56516 --- /dev/null +++ b/sock_http.cpp @@ -0,0 +1,205 @@ +#include "StdAfx.h" +#include "sock_http.h" +#include "_error.h" +#include "utiles_dll.h" + +#define INCREMENTO_MINIMO_SOC_HTTP 1024 + + +//******************************************************************** +Csock_http::Csock_http( C_error* e/*=NULL*/ ) +{ + buf=NULL; + n=m=0; + if (e) + { + er=e; + er_ex=TRUE; + } + else + { + er=new C_error(); + er_ex=FALSE; + } + pirate=FALSE; +} + +//******************************************************************** +Csock_http::~Csock_http(void) +{ + if (buf) + free(buf); + if (!er_ex && er) + delete er; +} +//******************************************************************** +BOOL Csock_http::cuida_mem( int i ) +{ + int incre=n+i-m; + if (incre>0) + { + if (increpon("Csock_http","Sin memoria"); + return FALSE; + } + memset(&buf[m-incre],0,incre); + } + return TRUE; +} +//******************************************************************** +BOOL Csock_http::carga( char *url, int puerto ) +{ + Cutiles_dll dll; + int i, nb;//,vec; + char *st; + char srv[256]; + Close(); + Create(); + n=0; + if (!cuida_mem(32+(int)strlen(url)+1)) + return FALSE; + st=strstr(url,"/"); + if (!st) + { + if(er) + er->pon("Csock_http", "Argumento url incorrecto"); + return FALSE; + } + + n=(int)strlen(buf); + //strcpy(srv,"http://"); + //nb=strlen(srv); + for (i=0; i<254 && st!=&url[i]; i++) + srv[i/*+nb*/]=url[i]; + + srv[i]=0; + nb=0; + sprintf(buf,"GET %s HTTP/1.1\r\nHOST: http://%s\r\n\r\n", st, srv); + //sprintf(buf, "GET /index.html HTTP/1.1\nHOST: %s\n\n",st,srv); + + if(!Connect(srv,puerto)) + { + i = GetLastError(); + if(i != WSAEWOULDBLOCK) + { + if (er) + { + er->pon_win("Csock_http"); + } + return FALSE; + } + } + + Sleep(1000); + //envia---------------------------------------------- + nb=n; + if(pirate) + { + if(er) + er->pon("Csock_http", "Salida forzosa"); + Close(); + return FALSE; + } + while(nb>0 && !pirate) + { + i=Send(&buf[n-nb],nb); + if (i<0) + { + i = GetLastError(); + if(i != WSAEWOULDBLOCK) + { + Close(); + if(er) + er->pon_win("Csock_http"); + return FALSE; + } + Sleep(100); + } + else + nb-=i; + } + if (pirate) + { + if(er) + er->pon("Csock_http", "Salida forzosa"); + Close(); + return FALSE; + } + //recibe----------------------------------------------------- + nb=n=0; + i=1; + while(nb<10000) + { + //revisa memoria-------------------------- + if (m-n<64 && !cuida_mem(128)) + { + if (er) + { + er->pon("Csock_http", "Sin memoria suficiente"); + } + Close(); + return FALSE; + } + i=Receive(&buf[n],m+1-n); + if (i<0) + { + i = GetLastError(); + if(i != WSAEWOULDBLOCK) + { + if (er) + { + er->pon_win("Csock_http"); + } + Close(); + return FALSE; + } + Sleep(10); + nb++; + } + else if(i==0) + nb++; + else + { + nb=0; + n+=i; + } + //fuerza salida---------------------------------- + if (pirate) + { + if(er) + er->pon("Csock_http", "Salida forzosa"); + Close(); + return FALSE; + } + } + Close(); + //asegura null---------------------------------------- + if (m-n<1) + { + if(!cuida_mem(1)) + { + if (er) + { + er->pon("Csock_http", "Sin memoria suficiente"); + } + return FALSE; + } + buf[n]=0; + n++; + } + return TRUE; +} +//******************************************************************** +char * Csock_http::get( int *nb ) +{ + if (n==0 && !buf) + return NULL; + return buf; +} +//******************************************************************** \ No newline at end of file diff --git a/sock_http.h b/sock_http.h new file mode 100644 index 0000000..ba0571b --- /dev/null +++ b/sock_http.h @@ -0,0 +1,26 @@ +#pragma once +#include "afxsock.h" +#include "base_head.h" +class C_error; +class UTILES_EXPORT Csock_http : + public CAsyncSocket +{ +public: + //variables--------------------------------- + int n,m;//indicadores del uso del buffer + char *buf;//buffer de almacenamiento + BOOL er_ex;//indica que la variable error es externa + BOOL pirate;//fuerza la salida del socket + C_error *er;//puntero a variable error + //c y d-------------------------------------- + Csock_http(C_error* e=NULL); + ~Csock_http(void); + //funciones---------------------------------- + BOOL carga(char *url, int puerto=80);//carga una url en concreto + char *get(int *nb);//devuelve el resultado de la carga +private: + BOOL cuida_mem(int n);//pide memo si hace falta + + + +}; diff --git a/sock_sv.cpp b/sock_sv.cpp new file mode 100644 index 0000000..c53bb81 --- /dev/null +++ b/sock_sv.cpp @@ -0,0 +1,173 @@ +#include "StdAfx.h" +#include "sock_sv.h" +#include "proceso_cliente.h" +#include "utiles_dll.h" +//******************************************************************** +Csock_sv::Csock_sv(BOOL*sal/*=NULL*/, C_error*e/*=NULL*/ ) +:Csock_cl(sal,e) +{ + sock_cerrado=FALSE; + crea_cliente=NULL; + escucha=NULL; +} +//******************************************************************** +Csock_sv::~Csock_sv(void) +{ + +} +//******************************************************************** +void Csock_sv::OnAccept( int nErrorCode ) +{ + int k; + BOOL del_soc; + SOCKADDR so; + if(pirate && *pirate) + goto salir; + Cproceso_cliente* cli=NULL; + if (escucha) + cli=escucha->crea_cliente(pirate); + else if (crea_cliente) + { + cli=crea_cliente(pirate); + } + + if (!cli) + goto salir; + del_soc=cli->soc==NULL; + if(del_soc) + cli->soc = new Csock_sv(pirate); + + k = sizeof(SOCKADDR); + if (!Accept( *cli->soc, &so,&k)) + { + if(del_soc) + delete cli->soc; + delete cli; + goto salir; + } + //if (strcmp(ss.logp,"DATOS")== 0 && ss.puerto_escucha==50056) + //pso->ss.nosalir=1; + + //pso->GetPeerName(cstr, port); + // proscrito, se hace en thread para no usar tiempo de mainthread + //strcpy(pso->ss.ipdot,cstr); + //pso->ss.puerto_llama = port; + //pso->ss.idu_usr = -1; + //ss.time = (UINT) time(NULL); + //pso->ss.time = ss.time; + + // crea thread para atender la consulta + cli->lanza("Proceso cliente"); +salir: + CAsyncSocket::OnAccept(nErrorCode); +} +//******************************************************************** +void Csock_sv::OnClose(int nErrorCode) +{ + sock_cerrado = TRUE; + CAsyncSocket::OnClose(nErrorCode); +} +//******************************************************************** +//******************************************************************** +//******************************************************************** +//******************************************************************** + +BOOL Csock_svThread::InitInstance() +{ + if(!CWinThread::InitInstance()) + AfxSocketInit(); + return TRUE; +} +//******************************************************************** +int Csock_svThread::Run() +{ + Csock_sv *sc = NULL; + sc = new Csock_sv(); + if(!sc) + goto va_mal; + sc->escucha = escucha; + sc->crea_cliente = crea_cliente; + + if (!sc->Create(port, + type,evenFlag, + url)) + { + goto va_mal; + } + if(!sc->Listen()) + goto va_mal; + isLisening = TRUE; + // Run message loop. + BOOL bRes = FALSE; + MSG msg; + while (!pireateTread) + { + while ( PeekMessage (&msg,NULL,NULL,NULL, + PM_NOREMOVE) ) + { + PeekMessage (&msg,NULL,NULL,NULL, + PM_REMOVE); + TranslateMessage(&msg); + DispatchMessage(&msg); + } + Sleep(100); + } +va_mal: + if(sc) + { + sc->Close(); + delete sc; + } + pireateTread = TRUE; + isLisening = FALSE; + + return (0) ; +} +//******************************************************************** +BOOL Csock_svThread::liseningThread( int port, char * url, int type, int evenFlag ) +{ + //AFX_MANAGE_STATE(AfxGetStaticModuleState()); + Cutiles_dll dll; + this->port =port; + this->type=type; + this->evenFlag = evenFlag; + this->url =url; + isLisening = FALSE; + pireateTread = FALSE; + + CreateThread(CREATE_SUSPENDED) ; + m_bAutoDelete = FALSE ; // Let me delete it. + sName = _T("Test") ; // Initialize something + ResumeThread() ; + while(!pireateTread) + { + if(isLisening) + return TRUE; + Sleep(100); + } + return FALSE; +} +//******************************************************************** +Csock_svThread::Csock_svThread() +{ + escucha = NULL; + crea_cliente =NULL; + isLisening = FALSE; + pireateTread = TRUE; +} +//******************************************************************** +void Csock_svThread::close() +{ + pireateTread = TRUE; + while(isLisening) + { + Sleep(10); + } +} +//******************************************************************** +Csock_svThread::~Csock_svThread() +{ + close(); + WaitForSingleObject(m_hThread, INFINITE); +} +//******************************************************************** \ No newline at end of file diff --git a/sock_sv.h b/sock_sv.h new file mode 100644 index 0000000..15a762a --- /dev/null +++ b/sock_sv.h @@ -0,0 +1,50 @@ +#pragma once +#include "Csock_cl.h" +#include "th.h" +#include +class Cproceso_cliente; +class UTILES_EXPORT Cescucha_sock_sv//interface para que te entren los accept +{ +public: + virtual Cproceso_cliente* crea_cliente(BOOL *pirate)=0;//funcion que crea los procesos cliente en el accept (devuelve null si no se acepta) +}; +//socket generico si se pone una escucha crea los socket cliente desde la escucha +//si no desde la funcion crea_cliente +//si el proceso cliente ya tiene un socket creado no se crea si no se crea un socket cliente +class UTILES_EXPORT Csock_sv : public Csock_cl +{ +public: + BOOL sock_cerrado; + Cescucha_sock_sv *escucha; + Csock_sv(BOOL* sal=NULL, C_error*e=NULL); + virtual ~Csock_sv(void); + Cproceso_cliente* (*crea_cliente)(BOOL *pirate ); + //funciones servidor------------------------------------ + virtual void OnAccept(int nErrorCode); + virtual void OnClose(int nErrorCode); + //virtual void run(); + //funciones virtuales de thread win +}; +//socket servidor con thread y cola de evntos propia + +class UTILES_EXPORT Csock_svThread :public CWinThread +{ + //DECLARE_DYNCREATE(Csock_svThread) + BOOL isLisening; + BOOL pireateTread; + int port, type, evenFlag; + char * url; + +public: + Cescucha_sock_sv *escucha; + Cproceso_cliente* (*crea_cliente)(BOOL *pirate ); + BOOL liseningThread(int port, char * url, int type = SOCK_STREAM, int evenFlag = FD_ACCEPT | FD_READ | FD_CLOSE );//inicia escucha + void close();//cierra escucha + //funciones aux------------------------ + ~Csock_svThread(); + Csock_svThread(); +//AfxSocketInit() + virtual BOOL InitInstance() ; + virtual int Run() ; + CString sName ;//nombre thread +}; \ No newline at end of file diff --git a/static_array.cpp b/static_array.cpp new file mode 100644 index 0000000..746a3f4 --- /dev/null +++ b/static_array.cpp @@ -0,0 +1,74 @@ +#include "StdAfx.h" +#include "static_array.h" +//********************************************************************* +Cstatic_array::Cstatic_array(int size) +{ + n=m=0; + buf=NULL; + z=size; + incremento=100; +} +//********************************************************************* +Cstatic_array::~Cstatic_array(void) +{ + borra(); +} +//********************************************************************* +void Cstatic_array::borra() +{ + n=m=0; + if (buf) + free(buf); + buf=NULL; + incremento=100; +} +//********************************************************************* +BOOL Cstatic_array::reserva( int p ) +{ + BYTE *bb; + if (n+p>m) + { + m+=incremento; + if (n>incremento) + m+=n; + if (buf) + bb=(BYTE*)realloc(buf,m*z); + else + bb=(BYTE*)malloc(m*z); + if(bb) + buf=bb; + else + return FALSE; + } + return TRUE; +} +//********************************************************************* +BYTE* Cstatic_array::get( int i ) +{ + if (i<0||i>=n) + return NULL; + return &buf[i*z]; +} +//********************************************************************* +void Cstatic_array::add( BYTE* e ) +{ + reserva(); + memcpy(&buf[n*z],e,z); + n++; +} +//********************************************************************* +BYTE* Cstatic_array::get_cp( int i ) +{ + BYTE* b; + BYTE* r; + b=get(i); + if (b) + { + r=(BYTE*)malloc(z); + memcpy(r,b,z); + return r; + } + return NULL; + +} +//********************************************************************* diff --git a/static_array.h b/static_array.h new file mode 100644 index 0000000..00191e9 --- /dev/null +++ b/static_array.h @@ -0,0 +1,20 @@ +#pragma once +#include "base_head.h" +class UTILES_EXPORT Cstatic_array +{ +public: + int z;//tamaño de la memoria + int n;//capacidad usada de la memoria + int m;//capacidad total de la memoria + int incremento; + BYTE* buf; + Cstatic_array(int size=1); + ~Cstatic_array(void); + //funciones--------------------------------------- + BYTE* get(int i);//da el elemento i + BYTE* get_cp(int i);//da una copia del elemento i + void add(BYTE* e);//añade elemento + void borra();//borra elementos + //funciones aux---------------------------------- + BOOL reserva(int p=1);//reserva memoria para p posiciones mas +}; diff --git a/static_array_ord.cpp b/static_array_ord.cpp new file mode 100644 index 0000000..e4da158 --- /dev/null +++ b/static_array_ord.cpp @@ -0,0 +1,141 @@ +#include "StdAfx.h" +#include "static_array_ord.h" +//*********************************************************************************** +Cstatic_array_ord::Cstatic_array_ord(void) +{ + comp_bus=NULL; + comp_add=NULL; +} +//*********************************************************************************** +Cstatic_array_ord::~Cstatic_array_ord(void) +{ + borra(); +} +//*********************************************************************************** +void Cstatic_array_ord::inicia( int size,int incremento/*=100*/ ) +{ + datos.z=size; + datos.incremento=incremento; + ind.z=sizeof(int); + ind.incremento=incremento; +} +//*********************************************************************************** +void Cstatic_array_ord::borra() +{ + datos.borra(); + ind.borra(); +} +//*********************************************************************************** +BYTE* Cstatic_array_ord::get( int i ) +{ + return datos.get((*(int*)ind.get(i))); +} +//*********************************************************************************** +BYTE* Cstatic_array_ord::get( BYTE* clave ) +{ + int i,f,c,r; + i=0; + f=ind.n; + c=ind.n/2; + BOOL enc=FALSE; + if (comp_bus==NULL) + return NULL; + //busqueda dicotomica------------------ + while(ci) + { + r=comp_bus(datos.get(*(int*)ind.get(c)),clave); + if (r<0) + f=r; + else if(r>0) + i=r; + else + { + enc=TRUE; + break; + } + c=(f-i)/2; + } + if(!enc) + { + if (comp_bus(datos.get(*(int*)ind.get(i)),clave)==0) + { + c=i; + enc=TRUE; + } + else if (comp_bus(datos.get(*(int*)ind.get(f)),clave)==0) + { + c=f; + enc=TRUE; + } + } + //fin busqueda dico----------------------------------- + if (enc) + return get(c); + else + return NULL; +} +//*********************************************************************************** +BYTE* Cstatic_array_ord::get_cp( int i ) +{ + return datos.get_cp((*(int*)ind.get(i))); +} +//*********************************************************************************** +void Cstatic_array_ord::agueca( int i ) +{ + BYTE* buf= (BYTE*)malloc(ind.z*2); + BYTE* ba1= buf; + BYTE* ba2= &buf[ind.z]; + BYTE* ba3; + if (i<0) + return; + memcpy(ba1,&ind.buf[ind.z*i],ind.z); + for (int j=i+1; ji) + { + r=comp_add(datos.get(*(int*)ind.get(c)),e); + if (r<0) + f=r; + else if(r>0) + i=r; + else + { + enc=TRUE; + break; + } + c=(f-i)/2; + } + //quedan como mucho 2 elementos + if (!enc) + { + if (comp_add(datos.get(*(int*)ind.get(i)),e)<=0) + c=i; + else + c=f; + } + //fin busqueda------------------------------------------ + agueca(c); + ind.add((BYTE*)&datos.n-1); +} +//*********************************************************************************** \ No newline at end of file diff --git a/static_array_ord.h b/static_array_ord.h new file mode 100644 index 0000000..e6b1549 --- /dev/null +++ b/static_array_ord.h @@ -0,0 +1,28 @@ +#pragma once +#include "static_array.h" +#include "base_head.h" +class UTILES_EXPORT Cstatic_array_ord//array ordenado de menor a mayor +{ +private: + //variables---------------------------- + Cstatic_array ind; + Cstatic_array datos; + + +public: + int (*comp_add)(BYTE* e1,BYTE*e2);//funcion de comparacion en añadir + int (*comp_bus)(BYTE* e1,BYTE* clave);//funcion de comparacion busqueda + Cstatic_array_ord(void); + ~Cstatic_array_ord(void); + + //funciones----------------------------- + void inicia(int size,int incremento=100);//establece el tamaño y el incremento(llamar solo una vez) + + BYTE* get(int i);//da el elemento de la posicion i + BYTE* get_cp(int i);//da copia del elemento de la posicion i + BYTE* get(BYTE* clave);//busca un elemento apartir de la clave + void add(BYTE* e); + void borra(); +private: + void agueca(int i);//mueve todos un puesto desde la posicion i dejando esta libre +}; diff --git a/static_cola.cpp b/static_cola.cpp new file mode 100644 index 0000000..baace5a --- /dev/null +++ b/static_cola.cpp @@ -0,0 +1,76 @@ +#include "StdAfx.h" +#include "static_cola.h" +//******************************************************************************* +Cstatic_cola::Cstatic_cola() +{ + capacidad=z=0; + ini=fin=0; + buf=NULL; + elemento=NULL; + +} +//******************************************************************************* +Cstatic_cola::~Cstatic_cola(void) +{ + if(buf) + free(buf); + if (elemento) + free(elemento); + +} +//******************************************************************************* +BOOL Cstatic_cola::add( BYTE *e ) +{ + cerrojo.entro();//<<<<<<<<<<<<<<<<< + //vemos si se puede---------------------- + if (ini==(fin+1)%capacidad) + { + cerrojo.salgo();//>>>>>>>>>>>>>> + return FALSE; + } + //ponemos sms---------------------------- + memcpy(&buf[fin*z],e,z); + fin=(fin+1)%capacidad; + cerrojo.salgo();//>>>>>>>>>>>>>> + return TRUE; +} + +BOOL Cstatic_cola::add( int t,BYTE *e ) +{ + cerrojo.entro();//<<<<<<<<<<<<<<<<< + //vemos si se puede---------------------- + if (ini==(fin+1)%capacidad) + { + cerrojo.salgo();//>>>>>>>>>>>>>> + return FALSE; + } + //ponemos sms---------------------------- + memcpy(&buf[fin*z],&t,sizeof(int)); + memcpy(&buf[fin*z+sizeof(int)],e,z); + fin=(fin+1)%capacidad; + cerrojo.salgo();//>>>>>>>>>>>>>> + return TRUE; +} + +//******************************************************************************* +void Cstatic_cola::inicia( int cap,int size ) +{ + z=size; + capacidad=cap; + ini=fin=0; + buf=(BYTE*)malloc(capacidad*z); + elemento=(BYTE*)malloc(z); +} +//******************************************************************************* +BYTE* Cstatic_cola::get() +{ + //vemos si hay pendientes--------------------- + if (ini==fin) + return NULL; + //pillamos------------------------------------ + memcpy(elemento,&buf[ini*z],z); + ini=(ini+1)%capacidad; + return elemento; +} + +//******************************************************************************* diff --git a/static_cola.h b/static_cola.h new file mode 100644 index 0000000..119d669 --- /dev/null +++ b/static_cola.h @@ -0,0 +1,25 @@ +#pragma once +#include "base_head.h" +#include "lock.h" +class UTILES_EXPORT Cstatic_cola +{ +public: + //variables + +private: + int z;//size de estructura; + int ini, fin; + int capacidad; + Clock cerrojo; + BYTE *buf; + BYTE *elemento; +public: + Cstatic_cola(); + ~Cstatic_cola(void); + //funciones----------------------------------------- + void inicia(int cap,int size); + BOOL add(BYTE *e);//concurrente + BYTE* get();//no concurrente + + BOOL add(int e1,BYTE *e2);//hecho para las colas (concurrente) +}; diff --git a/stdafx.cpp b/stdafx.cpp new file mode 100644 index 0000000..8e78903 --- /dev/null +++ b/stdafx.cpp @@ -0,0 +1,7 @@ +// stdafx.cpp : source file that includes just the standard includes +// utiles.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + diff --git a/stdafx.h b/stdafx.h new file mode 100644 index 0000000..93427e6 --- /dev/null +++ b/stdafx.h @@ -0,0 +1,41 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently + +#pragma once + +#ifndef VC_EXTRALEAN +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#endif + +#include "targetver.h" + +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit + +#include // MFC core and standard components +#include // MFC extensions + +#ifndef _AFX_NO_OLE_SUPPORT +#include // MFC OLE classes +#include // MFC OLE dialog classes +#include // MFC Automation classes +#endif // _AFX_NO_OLE_SUPPORT + +#ifndef _AFX_NO_DB_SUPPORT +#include // MFC ODBC database classes +#endif // _AFX_NO_DB_SUPPORT + +#ifndef _AFX_NO_DAO_SUPPORT +#include // MFC DAO database classes +#endif // _AFX_NO_DAO_SUPPORT + +#ifndef _AFX_NO_OLE_SUPPORT +#include // MFC support for Internet Explorer 4 Common Controls +#endif +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + +#include // MFC socket extensions + +#include "_log.h" \ No newline at end of file diff --git a/stdint.h b/stdint.h new file mode 100644 index 0000000..d02608a --- /dev/null +++ b/stdint.h @@ -0,0 +1,247 @@ +// ISO C9x compliant stdint.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006-2008 Alexander Chemeris +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. The name of the author may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_STDINT_H_ // [ +#define _MSC_STDINT_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +// For Visual Studio 6 in C++ mode and for many Visual Studio versions when +// compiling for ARM we should wrap include with 'extern "C++" {}' +// or compiler give many errors like this: +// error C2733: second C linkage of overloaded function 'wmemchr' not allowed +#ifdef __cplusplus +extern "C" { +#endif +# include +#ifdef __cplusplus +} +#endif + +// Define _W64 macros to mark types changing their size, like intptr_t. +#ifndef _W64 +# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 +# define _W64 __w64 +# else +# define _W64 +# endif +#endif + + +// 7.18.1 Integer types + +// 7.18.1.1 Exact-width integer types + +// Visual Studio 6 and Embedded Visual C++ 4 doesn't +// realize that, e.g. char has the same size as __int8 +// so we give up on __intX for them. +#if (_MSC_VER < 1300) + typedef signed char int8_t; + typedef signed short int16_t; + typedef signed int int32_t; + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; +#else + typedef signed __int8 int8_t; + typedef signed __int16 int16_t; + typedef signed __int32 int32_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; +#endif +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; + + +// 7.18.1.2 Minimum-width integer types +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; + +// 7.18.1.3 Fastest minimum-width integer types +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint16_t uint_fast16_t; +typedef uint32_t uint_fast32_t; +typedef uint64_t uint_fast64_t; + +// 7.18.1.4 Integer types capable of holding object pointers +#ifdef _WIN64 // [ + typedef signed __int64 intptr_t; + typedef unsigned __int64 uintptr_t; +#else // _WIN64 ][ + typedef _W64 signed int intptr_t; + typedef _W64 unsigned int uintptr_t; +#endif // _WIN64 ] + +// 7.18.1.5 Greatest-width integer types +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; + + +// 7.18.2 Limits of specified-width integer types + +#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 + +// 7.18.2.1 Limits of exact-width integer types +#define INT8_MIN ((int8_t)_I8_MIN) +#define INT8_MAX _I8_MAX +#define INT16_MIN ((int16_t)_I16_MIN) +#define INT16_MAX _I16_MAX +#define INT32_MIN ((int32_t)_I32_MIN) +#define INT32_MAX _I32_MAX +#define INT64_MIN ((int64_t)_I64_MIN) +#define INT64_MAX _I64_MAX +#define UINT8_MAX _UI8_MAX +#define UINT16_MAX _UI16_MAX +#define UINT32_MAX _UI32_MAX +#define UINT64_MAX _UI64_MAX + +// 7.18.2.2 Limits of minimum-width integer types +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +// 7.18.2.3 Limits of fastest minimum-width integer types +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +// 7.18.2.4 Limits of integer types capable of holding object pointers +#ifdef _WIN64 // [ +# define INTPTR_MIN INT64_MIN +# define INTPTR_MAX INT64_MAX +# define UINTPTR_MAX UINT64_MAX +#else // _WIN64 ][ +# define INTPTR_MIN INT32_MIN +# define INTPTR_MAX INT32_MAX +# define UINTPTR_MAX UINT32_MAX +#endif // _WIN64 ] + +// 7.18.2.5 Limits of greatest-width integer types +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +// 7.18.3 Limits of other integer types + +#ifdef _WIN64 // [ +# define PTRDIFF_MIN _I64_MIN +# define PTRDIFF_MAX _I64_MAX +#else // _WIN64 ][ +# define PTRDIFF_MIN _I32_MIN +# define PTRDIFF_MAX _I32_MAX +#endif // _WIN64 ] + +#define SIG_ATOMIC_MIN INT_MIN +#define SIG_ATOMIC_MAX INT_MAX + +#ifndef SIZE_MAX // [ +# ifdef _WIN64 // [ +# define SIZE_MAX _UI64_MAX +# else // _WIN64 ][ +# define SIZE_MAX _UI32_MAX +# endif // _WIN64 ] +#endif // SIZE_MAX ] + +// WCHAR_MIN and WCHAR_MAX are also defined in +#ifndef WCHAR_MIN // [ +# define WCHAR_MIN 0 +#endif // WCHAR_MIN ] +#ifndef WCHAR_MAX // [ +# define WCHAR_MAX _UI16_MAX +#endif // WCHAR_MAX ] + +#define WINT_MIN 0 +#define WINT_MAX _UI16_MAX + +#endif // __STDC_LIMIT_MACROS ] + + +// 7.18.4 Limits of other integer types + +#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 + +// 7.18.4.1 Macros for minimum-width integer constants + +#define INT8_C(val) val##i8 +#define INT16_C(val) val##i16 +#define INT32_C(val) val##i32 +#define INT64_C(val) val##i64 + +#define UINT8_C(val) val##ui8 +#define UINT16_C(val) val##ui16 +#define UINT32_C(val) val##ui32 +#define UINT64_C(val) val##ui64 + +// 7.18.4.2 Macros for greatest-width integer constants +#define INTMAX_C INT64_C +#define UINTMAX_C UINT64_C + +#endif // __STDC_CONSTANT_MACROS ] + + +#endif // _MSC_STDINT_H_ ] diff --git a/str_socket.cpp b/str_socket.cpp new file mode 100644 index 0000000..448f524 --- /dev/null +++ b/str_socket.cpp @@ -0,0 +1,481 @@ +#include "StdAfx.h" +#include "str_socket.h" + +#include "lock.h" +#include "utiles_dll.h" +//********************************************************************************************************************************** +Cstr_socket::Cstr_socket(void) +{ + buf=NULL; + n=m=0; + pirate=FALSE; + nb=0; + cli_currando=0; + pp=NULL; +} +//********************************************************************************************************************************** +Cstr_socket::~Cstr_socket(void) +{ + cierra(); + if(buf) + free(buf); +} +//********************************************************************************************************************************** + +BOOL Cstr_socket::crear( char *ip/*=NULL*/, int puerto/*=0*/ ) +{ + Cutiles_dll dll; + pirate=FALSE; + + BOOL resul = CAsyncSocket::Create(puerto, SOCK_STREAM,FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, + ip); + if (!resul) + er.pon_win("Cstr_socket"); + return resul; +} +//********************************************************************************************************************************** + +BOOL Cstr_socket::conecta( char *ip, int puerto ) +{ + fd_set rfds; + struct timeval tv; + FD_ZERO(&rfds); + char log_error[512]; + FD_SET(this->m_hSocket, &rfds); + tv.tv_sec = 5; + tv.tv_usec = 0; + int err,vez; + + if (!Connect(ip, puerto)) + { + err = GetLastError(); + if(err != WSAEWOULDBLOCK) + { + er.pon_win("Cstr_socket"); + return(FALSE); + } + } + + // ahora espera hasta que esté conectado + vez = 0; + do + { + int pruebaconexion = select(this->m_hSocket+1, NULL, &rfds, NULL, &tv); + if(pruebaconexion == 1) + break; + else if(pruebaconexion == SOCKET_ERROR) + err=WSAGetLastError(); + vez++; + Sleep(100); + if (vez > 50) // 5 segundos + { + + sprintf(log_error,"No puede conectar a IP %s %ld. Demasiado tiempo para conectar",ip, puerto); + er.pon("Cstr_socket",log_error,-1); + + return(FALSE); + } + + } while (!pirate); + + if(pirate) + { + er.pon("Cstr_socket","Error en conectar, pirate es true",-1); + return FALSE; + } + return(TRUE); +} +//********************************************************************************************************************************** +char* Cstr_socket::recibir() +{ + int nbb,k; + n=0; + //recibe numero de caracteres---------------------------- + nbb=recibir((BYTE*)&k,sizeof(int)); + if(nbb<0) + return NULL; + if(!nbb) + { + if(!cuida_mem(1)) + return NULL; + buf[0]=0; + n=1; + return buf; + } + if(k<=0) + { + er.pon("Cstr_socket", "Bloque defectuoso: número de caracteres 0 o negata"); + return NULL; + } + if(!cuida_mem(k+1)) + return NULL; + nb=k; + n=0; + while(k>0) + { + /*char st[128]; + sprintf(st,"quedan %ld, k=%ld\n",min(k,MAX_CHAR_BLOQ_STRSOCKET), k); + TRACE(st);*/ + nbb=recibir((BYTE*)&buf[n],min(k,MAX_CHAR_BLOQ_STRSOCKET)); + if(nbb<=0)//devuelve lo que se tenga hasta ahora + break; + n+=nbb; + k-=nbb; + } + buf[n]=0; + n++; + return buf; +} +//********************************************************************************************************************************** +int Cstr_socket::recibir( BYTE *b, int nbb ) +{ + int ini=0,k=0; + int veces=0; + do + { + k = Receive(&b[ini],nbb-ini); + if(k<0) + { + //e = GetLastError(); + if(GetLastError() != WSAEWOULDBLOCK ) + { + er.pon_win("Cstr_socket"); + return -1; + } + } + else if(k>0) + { + veces=0; + ini+=k; + if(ini>=nbb) + return ini; + continue; + } + else + { + k=GetLastError(); + if(k!=0) + k=k; + } + veces++; + if(veces>VECES_ESPERA_STRSOCKET) + { + er.pon("Cstr_socket","Error en recibir: superado el tiempo de espera",-1); + return(ini); + } + Sleep(ESPERA_STRSOCKET); + } while (!pirate); + er.pon("Cstr_socket","Error en recibir: Procesos cancelados por usuario",-1); + return(-1); +} +//********************************************************************************************************************************** +BOOL Cstr_socket::envia( char *fmt, ... ) +{ + n=0; + if(!cuida_mem(MIN_REALLOC_STR_SOC)) + return FALSE; + int k; + va_list arg_ptr; + va_start(arg_ptr, fmt); + do + { + k = _vsnprintf(buf,m, fmt, arg_ptr); + if(k<0) + { + n+=MIN_REALLOC_STR_SOC; + if(!cuida_mem(MIN_REALLOC_STR_SOC)) + break; + } + } while (k<0); + + va_end(arg_ptr); + if(k<0) + return FALSE; + n=strlen(buf); + k=0; + //envia numero de caracteres------------ + if(!enviar((int)sizeof(int),(BYTE*)&n)) + return FALSE; + while(n>0) + { + /*char st[512]; + sprintf(st,"Envio %ld, n=%ld\n",min(n,MAX_CHAR_BLOQ_STRSOCKET), n); + TRACE(st);*/ + if(!enviar( min(n, MAX_CHAR_BLOQ_STRSOCKET), (BYTE*)&buf[k])) + return FALSE; + n-=MAX_CHAR_BLOQ_STRSOCKET; + k+=MAX_CHAR_BLOQ_STRSOCKET; + } + n=0; + return TRUE; + +} +//********************************************************************************************************************************** +BOOL Cstr_socket::enviar(int nbb,BYTE *b) +{ + int ini=0, k, nv=0,e; + + + int ns,ib; + nv = ib = 0; + // envía al servidor + while (!pirate && nbb > 0) + { + k = Send(&b[ini],nbb,0); + if (k > 0) + { + ini+=k; + nbb-=k; + nv = 0; // reset tiempo espera + } + else + { + e = GetLastError(); + if (e == WSAENOTCONN) + { + ns = 0; + if (nv > VECES_ESPERA_STRSOCKET) + { + er.pon("Cstr_socket","Error no conectado al enviar, superado el tiempo de espera",-1); + + return(FALSE); + } + } + else if (e != WSAEWOULDBLOCK) + { + er.pon_win("Cstr_socket"); + return(FALSE); + } + nv++; + if (nv > (VECES_ESPERA_STRSOCKET)) + { + er.pon("Cstr_socket","Error al enviar, superardo el tiempo de espera",-1); + return(FALSE); + } + Sleep(ESPERA_STRSOCKET); + } + } + + if(pirate) + { + er.pon("Cstr_socket","Error al enviar: procesos cancelados por usuario",-1); + return FALSE; + } + return TRUE; + +} +//********************************************************************************************************************************** +BOOL Cstr_socket::cuida_mem( int nbb ) +{ + void *aux; + int incre=n+nbb-m; + if(incre<=0) + return TRUE; + if(incre0) + return buf; + n=0; + if(!cuida_mem(1)) + return NULL; + buf[0]=0; + n=1; + return buf; +} +//********************************************************************************************************************************** +void Cstr_socket_srv::OnAccept(int nErrorCode) +{ + int k; + SOCKADDR so; + if(pirate) + goto salir; + Cstr_socket_srv* cli=NULL; + cli=crea_cliente(); + cli->id_even=id_even; + cli->id_comman=id_comman; + + cli->sal_soc=&pirate; + cli->wnd=wnd; + cli->t_out=t_out; + + if (!cli) + goto salir; + + k = sizeof(SOCKADDR); + if (!Accept( *cli, &so,&k)) + { + delete cli; + goto salir; + } + + lck_sum_atm(&cli_currando,1); + cli->pp=this; + // crea thread para atender la consulta + AfxBeginThread(Cstr_socket_srv::th_funcion, (LPVOID)cli, THREAD_PRIORITY_NORMAL, 0, 0, NULL); +salir: + + Cstr_socket::OnAccept(nErrorCode); +} +//********************************************************************************************************************************** +void Cstr_socket_srv::run() +{ + t=_time64(NULL); + char *st; + Sleep(100); + while(!*sal_soc && !pirate) + { + st=recibir(); + if(!st) + { + pirate=TRUE; + continue; + } + if(!st[0]) + { + if((_time64(NULL)-t)>t_out) + { + pirate=TRUE; + continue; + } + } + else + { + t=_time64(NULL); + pirate=!on_datos_recibidos(st); + continue; + } + Sleep(10); + + } + if(pp) + (&pp->cli_currando,-1); + if(wnd) + PostMessage(wnd,id_comman,(WPARAM)id_even,(LPARAM)this);//para salir y destruir el socket +} +//********************************************************************************************************************************** +UINT Cstr_socket_srv::th_funcion( LPVOID pp ) +{ + ((Cstr_socket_srv*)pp)->run(); + return 0; +} +//********************************************************************************************************************************** +BOOL Cstr_socket_srv::pon_escucha( char *ip, int puerto ) +{ + if(!crear(ip,puerto)) + return FALSE; + if(!Listen()) + { + er.pon_win("Cstr_socket_srv"); + return FALSE; + } + return TRUE; +} +//********************************************************************************************************************************** +void Cstr_socket_srv::OnClose( int nErrorCode ) +{ + pirate=TRUE; + Cstr_socket::OnClose(nErrorCode); +} +//********************************************************************************************************************************** +Cstr_socket_srv::Cstr_socket_srv( void ) +{ + wnd=NULL; + id_even=0; + sal_soc=NULL; + t_out=60; + t=0; +} +//********************************************************************************************************************************** +Cstr_socket_srv::~Cstr_socket_srv( void ) +{ + +} +//********************************************************************************************************************************** +void Cstr_socket_srv::pon_wnd_destruc( HWND wnd,int id_comman,int id_even ) +{ + this->wnd=wnd; + this->id_comman=id_comman; + this->id_even=id_even; + +} +//********************************************************************************************************************************** +void Cstr_socket_srv::pon_tout( int t_out ) +{ + this->t_out = t_out; +} +//********************************************************************************************************************************** +//********************************************************************************************************************************** +extern "C" UTILES_EXPORT BOOL str_socket_conecta( Cstr_socket *soc, char *ip, int puerto ) +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + return soc->crear() && soc->conecta(ip, puerto); +} +//********************************************************************************************************************************** +extern "C" UTILES_EXPORT Cstr_socket * str_socket_crea() +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + return new Cstr_socket(); +} +//********************************************************************************************************************************** +extern "C" UTILES_EXPORT BOOL str_socket_envia( Cstr_socket *soc, char *txt ) +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + return soc->envia(txt); +} +//********************************************************************************************************************************** +extern "C" UTILES_EXPORT int str_socket_recive( Cstr_socket* soc ) +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + char *st=soc->recibir(); + if(!st) + return -1; + else + return strlen(st); +} +//********************************************************************************************************************************** +extern "C" UTILES_EXPORT void str_socket_dame_buf( Cstr_socket* soc, char* buf ) +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + char *st; + st=soc->getbuf(); + if(!st) + strcpy(buf,""); + else + strcpy(buf,st); + +} +//********************************************************************************************************************************** +extern "C" UTILES_EXPORT void str_socket_dame_error( Cstr_socket* soc, char* error ) +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + sprintf(error,"Mod: %s, desc:%s", soc->er.modulo,soc->er.msg); +} +//********************************************************************************************************************************** +extern "C" UTILES_EXPORT void str_socket_borra( Cstr_socket* soc ) +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + delete soc; +} +//********************************************************************************************************************************** \ No newline at end of file diff --git a/str_socket.h b/str_socket.h new file mode 100644 index 0000000..559f3fe --- /dev/null +++ b/str_socket.h @@ -0,0 +1,87 @@ +#pragma once +#include +#include "base_head.h" +#define MAX_CHAR_BLOQ_STRSOCKET 1024 //Maximo de caracteres por envio +#include "_error.h" + +#define ESPERA_STRSOCKET 1 //milis en sleep +#define ESPERA_SEG_STRSOCKET 3//SEGUNDOS MAXIMOS INTENTANDO RECIBIR ENVITOS +#define VECES_ESPERA_STRSOCKET ((1000 * ESPERA_SEG_STRSOCKET) / ESPERA_STRSOCKET) +#define MIN_REALLOC_STR_SOC 512 //bytes +/* +Socket cliente para envio de informacion ascii (string) +*/ +class UTILES_EXPORT Cstr_socket : public CAsyncSocket +{ +public: + //variables-------------------------------------- + C_error er;//variable que da info de posibles errores + BOOL pirate;//==TRUE -> se cancela todas las tareas del socket + long cli_currando;//indica que el socket esta en uso + Cstr_socket *pp; //puntero al padre + //variables aux---------------------------------- +private: + char *buf;//buffer de envios + int n, m;//ocupacion y capacidad del buffer + int nb;//indica el numero de bytes que va por envio total + +public: + //c y d------------------------------------------ + Cstr_socket(void); + ~Cstr_socket(void); +public: + //funciones-------------------------------------- + BOOL crear(char *ip=NULL, int puerto=0);//crea el socket en la ip y puerto de salida indicados + BOOL conecta(char *ip, int puerto);//contecta a servidor + char* recibir();//recibe string; + BOOL envia( char *fmt, ...);//envia string + void cierra();//cierra socket + char *getbuf();//devuelve buffer del socket + //funciones auxiliares--------------------------- +private: + BOOL cuida_mem(int nbb);//pide memoria si hace falta + int recibir(BYTE *b, int nbb);//recive nbb bytes y los deja en b + BOOL enviar(int nbb,BYTE *b); + +}; +/* +Socket servidor para envio de informacion ascii (string) +*/ +class UTILES_EXPORT Cstr_socket_srv : public Cstr_socket +{ + //variables aux---------------------------------- +private: + HWND wnd;//ventana a la que mandar eventos + int id_even, id_comman; + BOOL *sal_soc; + int t_out;//tiempo de salida sin hacer nada + __int64 t; +public: + //c y d------------------------------------------ + Cstr_socket_srv(void); + ~Cstr_socket_srv(void); + //funciones-------------------------------------- + virtual BOOL on_datos_recibidos(char *txt)=0;//funcion donde procesar los datos + virtual Cstr_socket_srv* crea_cliente()=0;//funcion donde procesar los datos + + BOOL pon_escucha(char *ip, int puerto); + void pon_wnd_destruc(HWND wnd,int id_comman,int id_even); + //funciones auxiliares--------------------------- +private: + + +public: + void run(); + virtual void OnAccept(int nErrorCode); + virtual void OnClose(int nErrorCode); + static UINT th_funcion(LPVOID pp); + void pon_tout( int t_out ); +}; +//funciones de socket cliente para pinvoke----------------------------------------------------- +extern "C" UTILES_EXPORT Cstr_socket *str_socket_crea(); +extern "C" UTILES_EXPORT BOOL str_socket_conecta(Cstr_socket *soc, char *ip, int puerto); +extern "C" UTILES_EXPORT BOOL str_socket_envia(Cstr_socket *soc, char *txt); +extern "C" UTILES_EXPORT int str_socket_recive(Cstr_socket* soc); +extern "C" UTILES_EXPORT void str_socket_dame_buf(Cstr_socket* soc, char* buf); +extern "C" UTILES_EXPORT void str_socket_dame_error(Cstr_socket* soc, char* error); +extern "C" UTILES_EXPORT void str_socket_borra(Cstr_socket* soc); \ No newline at end of file diff --git a/targetver.h b/targetver.h new file mode 100644 index 0000000..11730d5 --- /dev/null +++ b/targetver.h @@ -0,0 +1,26 @@ + +#pragma once + +// The following macros define the minimum required platform. The minimum required platform +// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run +// your application. The macros work by enabling all features available on platform versions up to and +// including the version specified. + +// Modify the following defines if you have to target a platform prior to the ones specified below. +// Refer to MSDN for the latest info on corresponding values for different platforms. +#ifndef WINVER // Specifies that the minimum required platform is Windows Vista. +#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. +#endif + +#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. +#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. +#endif + +#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. +#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. +#endif + +#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. +#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. +#endif + diff --git a/th.cpp b/th.cpp new file mode 100644 index 0000000..713f12c --- /dev/null +++ b/th.cpp @@ -0,0 +1,80 @@ +#include "StdAfx.h" +#include "th.h" + +#pragma pack(push,8) +typedef struct tagTHREADNAME_INFO +{ + DWORD dwType; // Must be 0x1000. + LPCSTR szName; // Pointer to name (in user addr space). + DWORD dwThreadID; // Thread ID (-1=caller thread). + DWORD dwFlags; // Reserved for future use, must be zero. +} THREADNAME_INFO; +#pragma pack(pop) +//****************************************************** +Cth::Cth(void) +{ + running =false; + strcpy(nombre, "Proceso sin nombre"); + m_thread=NULL; +} +//****************************************************** +Cth::~Cth(void) +{ + join(); +} +//****************************************************** +UINT main_th_proceso( LPVOID pp ) +{ + Cth *p=(Cth*)pp; + p->run(); + p->running = false; + AfxEndThread(0,FALSE); + return 0; +} +//****************************************************** +bool Cth::isRunning()//indica si se esta currando o no +{ + return running; +} +//****************************************************** +void Cth::join()//espera al thread +{ + if (m_thread == NULL) + return; + WaitForSingleObject(m_thread->m_hThread,INFINITE); + delete m_thread; + m_thread = NULL; +}; +//****************************************************** +BOOL Cth::lanza(char *nombre)//lanzar thread +{ + if (nombre) + strcpy(this->nombre,nombre); + m_thread = AfxBeginThread(main_th_proceso, this, THREAD_PRIORITY_NORMAL, 1024, CREATE_SUSPENDED); + m_thread->m_bAutoDelete=FALSE; + //pone el nombre------------------ +#ifdef _DEBUG + SetThName(m_thread->m_nThreadID,this->nombre); +#endif + running = true; + m_thread->ResumeThread(); + return TRUE; +}; +//****************************************************** +UTILES_EXPORT void SetThName( DWORD dwThreadID, char* threadName) +{ + THREADNAME_INFO info; + info.dwType = 0x1000; + info.szName = threadName; + info.dwThreadID = dwThreadID; + info.dwFlags = 0; + + __try + { + RaiseException( MS_VC_EXCEPTION_TH_UTILES, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info ); + } + __except(EXCEPTION_EXECUTE_HANDLER) + { + } +}; +//********************************************************************************************** \ No newline at end of file diff --git a/th.h b/th.h new file mode 100644 index 0000000..b2f91ea --- /dev/null +++ b/th.h @@ -0,0 +1,38 @@ +#pragma once +#ifndef INCLUDE_TH_UTILES +#define INCLUDE_TH_UTILES + +#include "base_head.h" +const DWORD MS_VC_EXCEPTION_TH_UTILES=0x406D1388; +//funciones necesarias------------- +UTILES_EXPORT void SetThName( DWORD dwThreadID, char* threadName); +UINT main_th_proceso(LPVOID pp); +//thead basico--------------------- +class UTILES_EXPORT Cth +{ + +public: + bool running;//variable interna no usar + //variables + + char nombre[32];//nombre del thread + CWinThread * m_thread;//puntero a thread + //cosntructor y destructor--------------- + Cth(void); + ~Cth(void); + //funicones------------------------------ + virtual void run()=0;//funcion que hace el thread + bool isRunning();//indica si se esta currando o no + + BOOL lanza(char *nombre=NULL);//lanzar thread + + //******************************** + void join();//espera a que el thread termine +}; + +class UTILES_EXPORT Crunable +{ +public: + virtual void frun(int modo=0)=0; +}; +#endif \ No newline at end of file diff --git a/th_cola.h b/th_cola.h new file mode 100644 index 0000000..065e11c --- /dev/null +++ b/th_cola.h @@ -0,0 +1,141 @@ +#pragma once +#include "th.h" +#include "gcola_con.h" + + +template +struct Timers_Cth_cola +{ + T tarea;//tarea a encadenar + __int64 t;//tiempo desde la ultima ejecucion + int dt;//periodo del timer +}; +//------------------------------------------------------------ +class Cth_rimers_cola : //tread para los timers + public Cth +{ +public: + Crunable *clase_run; + inline virtual void run() + { + clase_run->frun(0); + } +}; +//cola asincrona-------------------------------------------- +//thread de tareas tipico----------------------------------- +template +class Cth_cola : //falta probar, poner timers + public Cth, Crunable +{ +public: + Cgcola_con cola;//cola de tareas pendientes + Cgcola_con> timers;//tareas periodicas activas + BOOL pirate;//indica al tread que hay que terminar + BOOL eje_fin;//indica que hay que ejecutar la tarea final + int time_sleep;//tiempo de espera cuando no hay tareas + int tp_max;//maximo de tareas pendientes en cola + T tfin;//tarea final; + Cth_rimers_cola thtimers;//thread de control de tareas periodicas + //constructor y destructor-------------------------------- + //************************************************** + Cth_cola(void) + { + pirate=FALSE; + time_sleep=1; + tp_max=1000; + eje_fin=FALSE; + thtimers.clase_run=this; + thtimers.join(); + + + }; + //************************************************** + ~Cth_cola(void) + { + fin(); + }; + //funciones----------------------------------------------- + void pon_tfin(T &e) + { + tfin=e; + eje_fin=TRUE; + }; + //************************************************** + virtual inline BOOL operator+(T &e )//añade tarea + { + return !pirate && cola.n<=tp_max && cola+e; + }; + //************************************************** + virtual inline BOOL operator-(T &e )//añade tarea y elimina el resto + { + if (pirate) + return FALSE; + cola.cerrojo.entro(); + cola.borra(); + cola.cerrojo.salgo(); + return cola+e; + }; + //************************************************** + virtual void fin()//termina el proceso + { + pirate=TRUE; + thtimers.join(); + join(); + + }; + //************************************************** + BOOL pon_timer(int seg, T &tar)//pone una tarea periodica siendo t el periodo en seg + { + Timers_Cth_cola tim; + tim.t=0; + tim.tarea=tar; + tim.dt=seg; + timers+tim; + return TRUE; + }; + //************************************************** + virtual void procesa(T &t)//override de procesado que hay que sobreescribir + { + + }; + //************************************************** + virtual void run()//proceso que despacha + { + T tarea; + sprintf(thtimers.nombre,"%s_timers",nombre); + if (timers.n) + thtimers.lanza(); + while (!pirate) + { + if (cola-=&tarea) + procesa(tarea); + else + Sleep(time_sleep); + } + if(eje_fin) + procesa(tfin); + }; + //************************************************** + virtual void frun(int modo=0)//proceso del timer + { + __int64 t; + Element_Cgcola> *e; + while(!pirate) + { + timers.cerrojo.entro(); + e=timers.ini; + t=_time64(NULL); + while(e) + { + if (e->t.tt.tarea)) + e->t.t=t+e->t.dt; + } + e=e->sig; + } + Sleep(500); + } + }; + //************************************************** +}; diff --git a/utiles.cpp b/utiles.cpp new file mode 100644 index 0000000..f07d9cd --- /dev/null +++ b/utiles.cpp @@ -0,0 +1,78 @@ +// utiles.cpp : Defines the initialization routines for the DLL. +// + +#include "stdafx.h" +#include "utiles.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#endif + +// +//TODO: If this DLL is dynamically linked against the MFC DLLs, +// any functions exported from this DLL which call into +// MFC must have the AFX_MANAGE_STATE macro added at the +// very beginning of the function. +// +// For example: +// +// extern "C" BOOL PASCAL EXPORT ExportedFunction() +// { +// AFX_MANAGE_STATE(AfxGetStaticModuleState()); +// // normal function body here +// } +// +// It is very important that this macro appear in each +// function, prior to any calls into MFC. This means that +// it must appear as the first statement within the +// function, even before any object variable declarations +// as their constructors may generate calls into the MFC +// DLL. +// +// Please see MFC Technical Notes 33 and 58 for additional +// details. +// + +// CutilesApp + +BEGIN_MESSAGE_MAP(CutilesApp, CWinApp) +END_MESSAGE_MAP() + + +// CutilesApp construction + +CutilesApp::CutilesApp() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + + +// The one and only CutilesApp object + +CutilesApp theApp_utiles; + + +// CutilesApp initialization + +BOOL CutilesApp::InitInstance() +{ + CWinApp::InitInstance(); + + if (!AfxSocketInit()) + { + AfxMessageBox(IDP_SOCKETS_INIT_FAILED); + return FALSE; + } + hins_utiles=::LoadLibrary ("utiles.dll"); + hmod_utiles = ::GetModuleHandle("utiles.dll");//RT_BITMAP + + // Register all OLE server (factories) as running. This enables the + // OLE libraries to create objects from other applications. + COleObjectFactory::RegisterAll(); + return TRUE; +} + + + + diff --git a/utiles.def b/utiles.def new file mode 100644 index 0000000..72beb2d --- /dev/null +++ b/utiles.def @@ -0,0 +1,6 @@ +; utiles.def : Declares the module parameters for the DLL. + +LIBRARY "utiles" + +EXPORTS + ; Explicit exports can go here diff --git a/utiles.h b/utiles.h new file mode 100644 index 0000000..6893e84 --- /dev/null +++ b/utiles.h @@ -0,0 +1,30 @@ +// utiles.h : main header file for the utiles DLL +// + +#pragma once + +#ifndef __AFXWIN_H__ + #error "include 'stdafx.h' before including this file for PCH" +#endif + +#include "resource.h" // main symbols + + +// CutilesApp +// See utiles.cpp for the implementation of this class +// + +class CutilesApp : public CWinApp +{ +public: + CutilesApp(); + +// Overrides +public: + virtual BOOL InitInstance(); + + HINSTANCE hins_utiles; + HMODULE hmod_utiles; + DECLARE_MESSAGE_MAP() +}; +extern CutilesApp theApp_utiles; \ No newline at end of file diff --git a/utiles.rc b/utiles.rc new file mode 100644 index 0000000..9d9ec22 --- /dev/null +++ b/utiles.rc @@ -0,0 +1,139 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#ifndef APSTUDIO_INVOKED +#include "targetver.h" +#endif +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,8 + PRODUCTVERSION 1,0,0,8 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "Narvaling" + VALUE "FileDescription", "Librería de utilidades" + VALUE "FileVersion", "1.0.0.8" + VALUE "InternalName", "utiles.dll" + VALUE "OriginalFilename", "utiles.dll" + VALUE "ProductName", "Utiles" + VALUE "ProductVersion", "1.0.0.8" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// Spanish resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ESN) +#ifdef _WIN32 +LANGUAGE LANG_SPANISH, SUBLANG_SPANISH_MODERN +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#ifndef APSTUDIO_INVOKED\r\n" + "#include ""targetver.h""\r\n" + "#endif\r\n" + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1252)\r\n" + "#include ""res\\utiles.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // Spanish resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE 9, 1 +#pragma code_page(1252) +#include "res\utiles.rc2" // non-Microsoft Visual C++ edited resources +#include "afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/utiles.sln b/utiles.sln new file mode 100644 index 0000000..21afadb --- /dev/null +++ b/utiles.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28307.329 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "utiles", "utiles.vcxproj", "{AA58C828-7025-4A4C-868E-76B8902AF6BB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Debug|Win32.ActiveCfg = Debug|Win32 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Debug|Win32.Build.0 = Debug|Win32 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Debug|x64.ActiveCfg = Debug|x64 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Debug|x64.Build.0 = Debug|x64 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Release|Win32.ActiveCfg = Release|Win32 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Release|Win32.Build.0 = Release|Win32 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Release|x64.ActiveCfg = Release|x64 + {AA58C828-7025-4A4C-868E-76B8902AF6BB}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FE91DA93-025E-4149-A3B8-04A28F6B5A67} + EndGlobalSection +EndGlobal diff --git a/utiles.vcxproj b/utiles.vcxproj new file mode 100644 index 0000000..9e5aa04 --- /dev/null +++ b/utiles.vcxproj @@ -0,0 +1,352 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {AA58C828-7025-4A4C-868E-76B8902AF6BB} + utiles + MFCDLLProj + + + + DynamicLibrary + v141 + Dynamic + MultiByte + true + + + DynamicLibrary + v141 + Dynamic + MultiByte + + + DynamicLibrary + v141 + Dynamic + MultiByte + true + + + DynamicLibrary + v141 + Dynamic + MultiByte + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>15.0.28127.55 + + + Debug\ + $(Configuration)\ + true + + + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + + + Release\ + $(Configuration)\ + false + + + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + + + + _DEBUG;%(PreprocessorDefinitions) + false + + + Disabled + $(ProjectDir);%(AdditionalIncludeDirectories) + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + Level3 + EditAndContinue + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + Version.lib;%(AdditionalDependencies) + .\utiles.def + true + Windows + MachineX86 + + + copy $(OutDir)$(TargetFileName) ..\BIN\$(IntDir) +copy $(OutDir)\utiles.lib ..\lib\$(IntDir) + + + + + _DEBUG;%(PreprocessorDefinitions) + false + X64 + + + Disabled + $(ProjectDir);%(AdditionalIncludeDirectories) + WIN64;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + Level3 + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + Version.lib;%(AdditionalDependencies) + .\utiles.def + true + Windows + MachineX64 + + + copy $(OutDir)$(TargetFileName) ..\BIN\$(IntDir) +copy $(OutDir)\utiles.lib ..\lib\$(IntDir) + + + + + NDEBUG;%(PreprocessorDefinitions) + false + + + MaxSpeed + true + $(ProjectDir);%(AdditionalIncludeDirectories) + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level3 + ProgramDatabase + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + Version.lib;%(AdditionalDependencies) + .\utiles.def + true + Windows + true + true + MachineX86 + + + copy $(OutDir)$(TargetFileName) ..\BIN\$(IntDir) +copy $(OutDir)\utiles.lib ..\lib\$(IntDir) + + + + + NDEBUG;%(PreprocessorDefinitions) + false + X64 + + + MaxSpeed + true + $(ProjectDir);%(AdditionalIncludeDirectories) + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Use + Level3 + ProgramDatabase + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(IntDir);%(AdditionalIncludeDirectories) + + + Version.lib;%(AdditionalDependencies) + .\utiles.def + true + Windows + true + true + MachineX64 + + + copy $(OutDir)$(TargetFileName) ..\BIN\$(IntDir) +copy $(OutDir)\utiles.lib ..\lib\$(IntDir) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/utiles.vcxproj.filters b/utiles.vcxproj.filters new file mode 100644 index 0000000..30d8c94 --- /dev/null +++ b/utiles.vcxproj.filters @@ -0,0 +1,404 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {7b643c9b-19cf-464e-9b94-6ed0866d729b} + + + {fb3cfad6-9b35-48ac-adc6-4e9558cc8189} + + + {b9466878-19ac-4301-b054-2417262ccac4} + + + {85df11ce-492e-496e-bd30-87c63cee46c8} + + + {dc310809-598b-40d3-859b-d91b440bd579} + + + {b1f720e1-ca89-4141-9107-9abb4c47abfc} + + + {94603730-f909-4f29-96f0-5a4859f376c4} + + + {1b6a4130-a195-46c4-bd1b-0c85bf639da6} + + + {8e1bb5bd-4fbd-46f9-b415-17c99f585e42} + + + {4999dd29-4b4c-41d6-87d5-e7a3f0bc79a8} + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {edae31ee-1553-4484-b6e0-459bdae6939b} + + + {96a2c9e4-9dcf-429a-869d-059112717a51} + + + {682ae2c4-07d1-4652-bbff-a401260278ab} + + + {d73b3fec-8a4d-43dc-8010-e23a6f46e1b4} + + + {47389949-ef68-4fef-b9b7-59c61db4ac51} + + + {6264b6e5-6d23-4158-bd7c-32b28480c4b1} + + + {db92ca77-b400-4b58-a4f6-b44a2d9feb2c} + + + {848440f0-54ae-4d9e-9f40-50c1202c3284} + + + {500b4b80-8f59-44ab-82d2-1a645e9b1565} + + + {1be100f5-399d-4a42-af6f-06e3bce0759a} + + + {b59a9059-b3d5-410b-b730-f4bbb0fe2fa8} + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files\basico + + + Source Files\basico + + + Source Files\basico + + + Source Files\basico + + + Source Files\basico + + + Source Files\basico + + + Source Files\archivos + + + Source Files\archivos + + + Source Files\archivos + + + Source Files\archivos + + + Source Files\archivos + + + Source Files\archivos + + + Source Files\archivos + + + Source Files\archivos + + + Source Files\red + + + Source Files\red + + + Source Files\red + + + Source Files\red + + + Source Files\red + + + Source Files\array + + + Source Files\array + + + Source Files\array + + + Source Files\array + + + Source Files\thread + + + Source Files\thread + + + Source Files\tread_old + + + Source Files\tread_old + + + Source Files\basico_srv + + + Source Files\basico_srv + + + Source Files\pintado + + + Source Files\dijkstra + + + Source Files\dijkstra + + + Source Files\carto + + + Source Files\carto + + + Source Files\carto + + + Source Files\carto + + + Source Files\carto + + + Source Files\carto + + + + + Source Files + + + Resource Files + + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files\basico + + + Header Files\basico + + + Header Files\basico + + + Header Files\basico + + + Header Files\basico + + + Header Files\basico + + + Header Files\basico + + + Header Files\archivos + + + Header Files\archivos + + + Header Files\archivos + + + Header Files\archivos + + + Header Files\archivos + + + Header Files\archivos + + + Header Files\archivos + + + Header Files\archivos + + + Header Files\red + + + Header Files\red + + + Header Files\red + + + Header Files\red + + + Header Files\red + + + Header Files\array + + + Header Files\array + + + Header Files\array + + + Header Files\array + + + Header Files\thread + + + Header Files\thread + + + Header Files\thread + + + Header Files\garray + + + Header Files\garray + + + Header Files\garray + + + Header Files\garray + + + Header Files\garray + + + Header Files\garray + + + Header Files\tread_old + + + Header Files\tread_old + + + Header Files\basico_srv + + + Header Files\basico_srv + + + Header Files\pintado + + + Header Files\dijkstra + + + Header Files\dijkstra + + + Header Files\carto + + + Header Files\carto + + + Header Files\carto + + + Header Files\carto + + + Header Files\carto + + + Header Files\carto + + + Header Files\carto + + + + + Resource Files + + + \ No newline at end of file diff --git a/utiles_def.h b/utiles_def.h new file mode 100644 index 0000000..3c00f81 --- /dev/null +++ b/utiles_def.h @@ -0,0 +1,85 @@ +#pragma once +//defines de carpetas----------------------------------------------------------------------- + +#define D_WORK "%dir_work%" +#define D_LOG "%dir_log%" +#define D_APP "%dir_exe%" +#define D_DAT "%dir_dat%" +#define P_CONG "%p_config%" + +//define para comunicacion------------------------------------------------------------------ +#define VERSION_PACKAGE_HEAD 1 //version de metodo de comunicacion +#define MAX_LONG_PACKAGE_0 0x04000 //maximo de bytes por package +//flags de cabecera + +/* +#define FLAG_PACKAGE_HEAD_0_INICIO 0x00000001 +#define FLAG_PACKAGE_HEAD_0_CONTINUACION 0x00000002 +#define FLAG_PACKAGE_HEAD_0_FINAL 0x00000004*/ + +#define FLAG_PACKAGE_HEAD_0_ENCRIPT1 0x00000001 +#define FLAG_PACKAGE_HEAD_0_REPLICADO 0x00000002 +//estructuras para comunicacion------------------------------------------------------------- +typedef struct Package_head_0//cabecera base de la cumunicación +{ + int version; //version de comunicacion + int flags; //flags + int nb; //numero de bytes del paquete + int n; //numero de bloques de este paquete +}Package_head_0; +//en esta version el identificador de los paquetes sera un entero (int) +//paquetes generales de envio---------------------------------------------------------------- +#define PETICION_GENERAL_NO 0//paquete de negacion + +#define PETICION_GENERAL_PRESENTA 1//peticion de presentacion usuario y key +#define PETICION_GENERAL_OK 2//respuesta ok automatica +#define PETICION_GENERAL_DESCONECTA 3//peticion de desconexion +#define PETICION_GENERAL_DAME_LOG 4//peticion de eventos (normalmente con id) +#define PETICION_GENERAL_TOMA_COMANDO 5//peticionde comando para servidor +#define PETICION_GENERAL_FIN 6 + + +//define para usuarios------------------------------------------------------------------------ +#define VERSION_USUARIO_CONEXION 1 //version de usuarios +//flags usuarios +#define FLAG_USUARIO_CONEXION_INDI 0x00000001//indica que solo se acepta una conexion por dicho usuario +#define FLAG_USUARIO_CONEXION_EN_USO 0x00000002//indica que el usuario esta en uso actualmente +#define FLAG_USUARIO_CONEXION_VACIO 0x00000004//indica que el usuario esta borrado +#define FLAG_USUARIO_CONEXION_BLOQ 0x00000008//indica que el usuario esta bloqueado (no se puede usar) +//flags archivo +#define FLAG_FILE_USUARIO_CONEX_ENCRIP 0x00000001//indica que el archivo esta encriptado +//flags permisos + +//estructura para usuarios--------------------------------------------------------------------- +typedef struct Usuario_conx_0//informacion de usuario +{ + int flags; + int id; //identificador de usuario + int permisos; //flags de permisos + int ia; //informacion adicional + int ncon; //numero de conectados con este usuario + char nombre[32]; //nombre de usuario + char clave[32]; //calve de usuario +}Usuario_conx_0; + +typedef struct Head_usuario_conex_0//cabecera de archivo de usuario +{ + int version; //version informacion de usuaros + int flags; //flags + int n; //numero de usuarios en archivo +}Head_usuario_conex_0; + +//interface de elemento que se transfiere---------------------------------- +class IdataTransfer +{ +public: + //para lectura + virtual __int64 getNB_it()=0;//devuelve numero de bites totales de informacion + virtual __int64 getNext_it(void* buf,__int64 nb)=0;//copia en buffer buf el los siguientes nb bytes y devuelve el numero total de bites leidos + + //lectura y escritura + inline virtual bool setPosition_it(__int64 nb){ return false; };//se posiciona en el byte nb los datos + + //para escritura----------- + inline virtual bool set_it(void* buf, __int64 nb){ return true; };//prepara datos para recivir nb bites +}; \ No newline at end of file diff --git a/utiles_dll.cpp b/utiles_dll.cpp new file mode 100644 index 0000000..8a5bb05 --- /dev/null +++ b/utiles_dll.cpp @@ -0,0 +1,13 @@ +#include "StdAfx.h" +#include "utiles_dll.h" +#include "utiles.h" +Cutiles_dll::Cutiles_dll(void) +{ + m_hInstOld = AfxGetResourceHandle(); + AfxSetResourceHandle(theApp_utiles.hmod_utiles); +} + +Cutiles_dll::~Cutiles_dll(void) +{ +AfxSetResourceHandle(m_hInstOld); +} diff --git a/utiles_dll.h b/utiles_dll.h new file mode 100644 index 0000000..13da430 --- /dev/null +++ b/utiles_dll.h @@ -0,0 +1,9 @@ +#pragma once + +class Cutiles_dll +{ +public: + HINSTANCE m_hInstOld; + Cutiles_dll(void); + virtual ~Cutiles_dll(void); +}; diff --git a/utl.cpp b/utl.cpp new file mode 100644 index 0000000..ffdd97d --- /dev/null +++ b/utl.cpp @@ -0,0 +1,462 @@ +#include "StdAfx.h" +#include "utl.h" +#include "StrArray.h" +#include +#include + +//************************************************************************** +Cutl::Cutl(void) +{ +} +//************************************************************************** + +Cutl::~Cutl(void) +{ +} +//************************************************************************** +void Cutl::big_little( BYTE* b,int nb ) +{ + BYTE*aux=(BYTE*)malloc(nb); + for (int i=0;i>1); + bit=bit|((b[i]& 0x08)>>3); + bit=bit|((b[i]& 0x10)<<3); + bit=bit|((b[i]& 0x20)<<1); + bit=bit|((b[i]& 0x40)>>1); + bit=bit|((b[i]& 0x80)>>3); + //inverso---------------- + if (i%2==0) + bit=~bit; + else + bit=bit; + + //orden------------------ + if (i==0) + { + n=255-bit-(char)(nb%256); + aux[0]=bit; + } + else + aux[1+(n1+i)%(nb-1)]=bit-n; + } + memcpy(b,aux,nb); + free(aux); +} +//*************************************************************************** +void Cutl::cifra1( char*b ) +{ + cifra1((BYTE*)b,(int)strlen(b)); +} + +//*************************************************************************** +void Cutl::descifra1( BYTE* b,int nb ) +{ + BYTE *aux=(BYTE*)malloc(nb); + BYTE bit; + BYTE bit1; + char n=0; + int n1=(nb-1)/2; + + for (int i=0;i>1); + bit=bit|((bit1& 0x08)>>3); + bit=bit|((bit1& 0x10)<<3); + bit=bit|((bit1& 0x20)<<1); + bit=bit|((bit1& 0x40)>>1); + bit=bit|((bit1& 0x80)>>3); + aux[i]=bit; + } + memcpy(b,aux,nb); + free(aux); +} +//*************************************************************************** +void Cutl::descifra1( char*b ) +{ + descifra1((BYTE*)b,(int)strlen(b)); +} +//*************************************************************************** +int Cutl::busca( BYTE*lista,int n,int z,BYTE *e, int (*funcion)(BYTE*,BYTE*) ) +{ + int i,f,c,r; + i=0; + f=n-1; + c=n/2; + while(ci) + { + r=funcion(&lista[z*c],e); + if (r<0) + f=r; + else if(r>0) + i=r; + else + return c; + c=(f-i)/2; + } + //quedan como mucho 2 elementos + if (funcion(&lista[z*i],e)<=0) + return i; + return f; +} +//******************************************************************************************** +int pon_id(char* idm, int nb, int nbAct, char *buf, int nbbuf ) +{ + int i; + for(i=0; i10) + return NULL; + continue; + } + if(ERROR_SUCCESS!=er) + return NULL; + ii=pon_id(idm, nb,ii,str,strlen(str)); + } + RegCloseKey( hKey1); + + er = RegOpenKeyEx ( HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\BIOS", 0,KEY_READ,&hKey1); + if (er != ERROR_SUCCESS) + { + return NULL; + } + for (i=0; i<12; i++) + { + l2=2048; + er=RegQueryValueEx(hKey1,prop_bios[i],0,NULL,(LPBYTE) str,(LPDWORD) &l2); + if(er==ERROR_FILE_NOT_FOUND) + { + v_er++; + if(v_er>10) + return NULL; + continue; + } + if(ERROR_SUCCESS!=er) + return NULL; + ii=pon_id(idm, nb,ii,str,strlen(str)); + } + RegCloseKey( hKey1); + + er = RegOpenKeyEx ( HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,KEY_READ,&hKey1); + if (er != ERROR_SUCCESS) + { + return NULL; + } + for (i=0; i<3; i++) + { + l2=2048; + er=RegQueryValueEx(hKey1,prop_proce[i],0,NULL,(LPBYTE) str,(LPDWORD) &l2); + if(er==ERROR_FILE_NOT_FOUND) + { + v_er++; + if(v_er>10) + return NULL; + continue; + } + if(ERROR_SUCCESS!=er) + return NULL; + ii=pon_id(idm, nb,ii,str,strlen(str)); + } + + + for (; i<5; i++) + { + l2 = sizeof(DWORD); + er=RegQueryValueEx(hKey1, prop_proce[i], NULL, NULL, (LPBYTE)&dwData, (LPDWORD)&l2); + if(ERROR_SUCCESS!=er) + { + v_er++; + if(v_er>10) + return FALSE; + continue; + } + sprintf(str,"%u",dwData); + ii=pon_id(idm, nb,ii,str,strlen(str)); + } + + //QueryPerformanceFrequency( &lpFrequency); + + //RegQueryValueEx(hKey1,prop_proce[i],0,NULL,(LPBYTE) &dd,(LPDWORD) &l2); + // sprintf(str,"%ld",i); + //l2=strlen(str); + //ii=pon_id(id,ii,(char*)&lpFrequency,sizeof(LARGE_INTEGER)); + + RegCloseKey( hKey1); + + //lo pasa a string + int n1='z'-'a'+1; + int n2='Z'-'A'+1; + int nt=n1+n2+'9'-'0'+1; + for (i=0; i='0' && *s<='9') + res=(res<<4)|(int)(*s-'0'); + else if(*s>='a' && *s<='f') + res=(res<<4)|(10+(int)(*s-'a')); + else if(*s>='A' && *s<='F') + res=(res<<4)|(10+(int)(*s-'A')); + else + break; + s++; + } + return res; +} +//*************************************************************************** +void Cutl::int2str_hex( char* st , int n) +{ + int i,a; + strcpy(st,"0x00000000"); + for(i=0; i<8; i++) + { + a=(n>>4*i)&0xf; + if(a<10) + st[2+7-i]='0'+(char)a; + else + st[2+7-i]='a'+(char)a-10; + } + +} +//*************************************************************************** +DWORDLONG Cutl::getMemoDisp() +{ + MEMORYSTATUSEX status; + status.dwLength = sizeof(status); + GlobalMemoryStatusEx(&status); + return status.ullAvailVirtual; +} +//*************************************************************************** +bool Cutl::lanza_exe(char *appName, char *comline, DWORD *processId) +{ + // additional information + STARTUPINFO si; + PROCESS_INFORMATION pi; + BOOL is_alive=FALSE; + + // set the size of the structures + ZeroMemory( &si, sizeof(si) ); + si.cb = sizeof(si); + ZeroMemory( &pi, sizeof(pi) ); + + // start the program up + CreateProcess( appName, // the path + comline, // Command line + NULL, // Process handle not inheritable + NULL, // Thread handle not inheritable + FALSE, // Set handle inheritance to FALSE + 0, // No creation flags + NULL, // Use parent's environment block + NULL, // Use parent's starting directory + &si, // Pointer to STARTUPINFO structure + &pi // Pointer to PROCESS_INFORMATION structure (removed extra parentheses) + ); + + //check is alive + DWORD lpExitCode; + GetExitCodeProcess(pi.hProcess,&lpExitCode); + is_alive=(lpExitCode==STILL_ACTIVE); + + // Close process and thread handles. + CloseHandle( pi.hProcess ); + CloseHandle( pi.hThread ); + if(is_alive==TRUE && processId) + *processId=pi.dwProcessId; + return is_alive==TRUE; +} +//*************************************************************************** +DWORDLONG Cutl::getMemoDisp1Malloc() +{ + void* bufprinci = NULL; + //en un malloc----------------------- + DWORDLONG i=0; + DWORDLONG paso; + //ia=paso; + //for (int j=0; j<3; j++) + //{ + paso=1024*1024*1024; + while(TRUE) + { + bufprinci=malloc(size_t(i+paso)); + if (bufprinci) + { + free(bufprinci); + i+=paso; + } + else + { + if (paso<1) + break; + paso=paso/2; + if (paso<1) + break; + } + } + if (bufprinci) + free(bufprinci); + return i; +} +//*************************************************************************** +StrArray* Cutl::stringSplit( char *orig,char* subStr, StrArray*buf ) +{ + char *s = orig; + char *s1, *s2; + int siz =strlen(subStr); + s1 = strstr(s, subStr); + int n; + while(s1) + { + n = (int)(s1-s); + buf->add(NULL, n+1); + s2 = buf->get(buf->n_i-1); + if(!s1) + return NULL; + for (int i =0; iadd(s); + s2 = buf->get(buf->n_i-1); + if(!s2) + return NULL; + return buf; +} +//*************************************************************************** +char* Cutl::getWinUser( char* buf ) +{ + DWORD username_len = UNLEN+1; + GetUserName(buf, &username_len); + return buf; +} + +//*************************************************************************** diff --git a/utl.h b/utl.h new file mode 100644 index 0000000..7b3b388 --- /dev/null +++ b/utl.h @@ -0,0 +1,33 @@ +#pragma once +#include "base_head.h" +class StrArray; +class UTILES_EXPORT Cutl +{ +public: + Cutl(void); + ~Cutl(void); + //cifra y descifra datos con FLAG_PACKAGE_HEAD_0_ENCRIPT1 + static void cifra1(BYTE*b,int nb); + static void cifra1(char*b);//ojo con los char despues de cifrar no usar stlen ni semejantes + static void descifra1(char*b); + static void descifra1(BYTE* b,int nb); + //-------------------------------------------------------- + static void big_little(BYTE* b,int nb);//cambia de little a big_endian y viceversa + //ordenacion---------------------------------------------- + static int busca(BYTE*lista,int n,int sizeElement,BYTE *e, int (*funcion)(BYTE*,BYTE*) );//busqueda dicotomica + static StrArray* stringSplit(char *orig,char* subStr, StrArray*buf); + + //identificador pc---------------------------------------- + static char* id_pc(char*idm, int nb);//proporciona un identificador unico de la computadora + static DWORDLONG getMemoDisp();//devuelve la memoria disponible + static DWORDLONG getMemoDisp1Malloc();//devuelve la memoria disponible real en mem1 en un malloc + + //identificacion de usuario de windows-------------------- + static char* getWinUser(char* buf);//leng de 256 + + //funciones de string-------------------------------- + static int str_hex2int(char* st);//pasa de cadena de caracteres tipo 0xff a entero + static void int2str_hex( char* st , int n); + + static bool lanza_exe(char *appName, char *comline, DWORD *processId = NULL);//ejecuta appName +};