Tải bản đầy đủ - 0 (trang)
5 ISAM (Indexed Sequential Access Method) Files

5 ISAM (Indexed Sequential Access Method) Files

Tải bản đầy đủ - 0trang

forever

<>



fileio.position(fileHandle);

mov(eax,ISAMarray[ecx*4]);//Saveawaycurrentreco

fileio.put(fileHandle,outputLine,nl);//Writethe

inc(ecx);//AdvancetonextelementofISAMarray.

<>

endfor;



<

<

<>

Afterbuildingthefileusingthecodeabove,youcanquicklyjumptoan

arbitrarylineoftextbyfetchingtheindexforthatlinefromthe

ISAMarraylist.Thefollowingcodedemonstrateshowyoucouldread

linerecordNumberfromthefile:



mov(recordNumber,ebx);



fileio.seek(fileHandle,ISAMarray[ebx*4]);



fileio.a_gets(fileHandle,inputString);

Aslongasyou'veprecalculatedtheISAMarraylist,accessingan

arbitrarylineinthistextfileisatrivialmatter.

Ofcourse,backinthedayswhenIBMprogrammersweretryingto

squeezeeverybytefromtheirdatabasesaspossiblesotheywouldfiton

a5MBdiskdrive,theydidn'thave512kilobytesofRAMtohold128K

entriesintheISAMarraylist.Althoughahalfamegabyteisnobigdeal

today,thereareacoupleofreasonswhykeepingtheISAMarraylistina

memory-basedarraymightnotbesuchagoodidea.First,databasesare

muchlargerthesedays.Somedatabaseshavehundredsofmillionsof

entries.WhilesettingasideahalfamegabyteforanISAMtablemight

notbeabadthing,fewpeoplearewillingtosetasideahalfagigabyte



forthispurpose.Evenifyourdatabaseisn'tamazinglybig,thereis

anotherreasonwhyyoumightnotwanttokeepyourISAMarrayinmain

memory;it'sthesamereasonyoudon'tkeepthefileinmemory:Memory

isvolatile,andthedataislostwhenevertheapplicationquitsortheuser

removespowerfromthesystem.Thesolutionisexactlythesameasfor

thefiledata:YoustoretheISAMarraydatainitsownfile.Aprogram

thatbuildstheISAMtablewhilewritingthefileisasimplemodificationto

thepreviousISAMgenerationprogram.Thetrickistoopentwofiles

concurrentlyandwritetheISAMdatatoonefilewhileyou'rewritingthe

texttotheotherfile:

static

fileHandle:dword;//filehandleforthetextfile.

outputLine:string;//filehandlefortheISAMfile.

CurrentOffset:dword;//Holdsthecurrentoffsetintothe

.

.

.

forever

<>



//Gettheoffsetofthenextrecordinthetextfile

//andwritethisoffset(sequentially)totheISAMf



fileio.position(fileHandle);

mov(eax,CurrentOffset);

fileio.write(isamHandle,(typebyteCurrentOffset),



//Okay,writetheactualtextdatatothetextfile:



fileio.put(fileHandle,outputLine,nl);//Writeth

<>

endfor;

Ifnecessary,youcancountthenumberofrecordsasbefore.Youmight



writethisvaluetothefirstrecordoftheISAMfile(becauseyouknowthe

firstrecordofthetextfileisalwaysatoffsetzero,youcanusethefirst

elementoftheISAMlisttoholdthecountofISAM/textfilerecords).



BecausetheISAMfileisjustasequenceoffour-byteintegers,each

recordinthefile(i.e.,aninteger)hasthesamelength.Therefore,wecan

easilyaccessanyvalueintheISAMfileusingtherandomaccessfileI/O

mechanism.Inordertoreadaparticularlineoftextfromthetextfile,the

firsttaskistoreadtheoffsetfromtheISAMfileandthenusethatoffsetto

readthedesiredlinefromthetextfile.Thecodetoaccomplishthisisas

follows:

//Assumewewanttoreadthelinespecifiedbythe"lineN



if(lineNumber<>0)then

//Ifnotrecordnumberzero,thenfetchtheoffsettothe

//linefromtheISAMfile:



intmul(4,lineNumber,eax);//Computetheindexintoth

fileio.seek(isamHandle,eax);

fileio.read(isamHandle,(typebyteCurrentOffset),4);/

else

mov(0,eax);//Specialcaseforrecordzerobecausethe

//containstherecordcountinthispositi



endif;

fileio.seek(fileHandle,CurrentOffset);//Settextfileposi

fileio.a_gets(fileHandle,inputLine);//Readthelineoft

ThisoperationrunsatabouthalfthespeedofhavingtheISAMarrayin

memory(becauseittakesfourfileaccessesratherthantwotoreadthe

lineoftextfromthefile),butthedataisnon-volatileandisnotlimitedby

theamountofavailableRAM.

Ifyoudecidetouseamemory-basedarrayforyourISAMtable,it'sstilla

goodideatokeepthatdatainafilesomewheresoyoudon'thaveto

recomputeit(byreadingtheentirefile)everytimeyourapplicationstarts.

Ifthedataispresentinafile,allyou'vegottodoisreadthatfiledatainto



yourISAMarraylist.Assumingyou'vestoredthenumberofrecordsin

elementnumberzerooftheISAMarray,youcouldusethefollowingcode

toreadyourISAMdataintotheISAMarrayvariable:



static

isamSize:uns32;

isamHandle:dword;

fileHandle:dword;

ISAMarray:dword[128*1024];

.

.

.

//ReadthefirstrecordoftheISAMfileintotheisamSiz

fileio.read(isamHandle,(typebyteisamSize),4);



//NowreadtheremainingdatafromtheISAMfileintothe

//variable:

if(isamSize>=128*1024)then

raise(ex.ValueOutOfRange);



endif;

intmul(4,isamSize,ecx);//#records*4isnumberofb

fileio.read(isamHandle,(typebyteISAMarray),ecx);

//Atthispoint,ISAMarray[0]..ISAMarray[isamSize-1]cont

//intothetextfileforeachlineoftext.

[3]Redundantarrayofinexpensivedisks.RAIDisamechanismfor

combininglotsofcheapdiskdrivestogethertoformtheequivalentofa

reallylargediskdrive.

[4]Thisassumes,ofcourse,thatyourfileshaveamaximumsizeoffour

gigabytes.



8.6TruncatingaFile

Ifyouopenanexistingfile(usingfileio.open)foroutputandwrite

datatothatfile,itoverwritestheexistingdatafromthestartofthefile.

However,ifthenewdatayouwritetothefileisshorterthanthedata

originallyappearinginthefile,theexcessdatafromtheoriginalfile,

beyondtheendofthenewdatayou'vewritten,willstillappearattheend

ofthenewdata.Sometimesthismightbedesirable,butmostofthetime,

you'llwanttodeletetheolddataafterwritingthenewdata.

Onewaytodeletetheolddataistousethefileio.opennewfunction

toopenthefile.Thefileio.opennewfunctionautomaticallydeletes

anyexistingfilesoonlythedatayouwritetothefilewillbepresentinthe

file.However,theremaybetimeswhenyoumaywanttoreadtheold

datafirst,rewindthefile,andthenoverwritethedata.Inthissituation,

you'llneedafunctionthatwilltruncatetheolddataattheendofthefile

afteryou'vewrittenthenewdata.Thefileio.truncatefunction

accomplishesthistask.Thisfunctionusesthefollowingcallingsyntax:

fileio.truncate(fileHandle);

Notethatthisfunctiondoesnotclosethefile.Youstillhavetocall

fileio.closetocommitthedatatothedisk.

TheprograminListing8-7demonstratestheuseofthe

fileio.truncatefunction.

Listing8-7:Usingfileio.truncatetoEliminateOldDatafromaFile.

programTruncateDemo;

#include("stdlib.hhf")

static

fileHandle:dword;

u:uns32;

beginTruncateDemo;



fileio.openNew("myfile.txt");

mov(eax,fileHandle);

for(mov(0,ecx);ecx<20;inc(ecx))do

fileio.put(fileHandle,(typeuns32ecx),nl);

endfor;

//Okay,let'srewindtothebeginningofthefileand

//rewritethefirsttenlinesandthentruncatethe

//fileatthatpoint.

fileio.rewind(fileHandle);

for(mov(0,ecx);ecx<10;inc(ecx))do

fileio.put(fileHandle,(typeuns32ecx),nl);

endfor;

fileio.truncate(fileHandle);



//Rewindanddisplaythefilecontentstoensurethat

//thefiletruncationhasworked.

fileio.rewind(fileHandle);

while(!fileio.eof(fileHandle))do

//Readanddisplaythenextitemfromthefile:

fileio.get(fileHandle,u);

stdout.put("u=",u,nl);

fileio.readLn(fileHandle);

endwhile;

fileio.close(fileHandle);

endTruncateDemo;



8.7ForMoreInformation

Mostoftheinformationappearinginthischapterisgeneric—thatis,it's

notassemblylanguagespecific.Assuch,you'llfindawealthof

informationonfileI/Oindatastructuretextsandotherintroductory

programmingtexts.TheHLAStandardLibraryprovideshundredsof

functionsandproceduresrelatedtofileI/O.Formoreinformationon

those,pleaseconsulttheHLAStandardLibraryReferenceManual.

Ifyou'reinterestedinimplementingadatabaseengineinassembly

language,youshoulddefinitelyconsiderobtainingacollegetextbookon

databasedesign.Althoughsuchtextsalmostalwaysuseahighlevel

language,mostofthetheoreticalinformationappearinginsuchtextsis

languageindependent,andyou'llfinditquiteusefulwhenworkingon

yourassemblydatabaseengine.



Chapter9:AdvancedArithmetic

DownloadCDContent



9.1ChapterOverview

Thischapterdealswiththosearithmeticoperationsforwhichassembly

languageisespeciallywellsuited,butforwhichhighlevellanguagesare,

ingeneral,poorlysuited.Itcoversfourmaintopics:extendedprecision

arithmetic,arithmeticonoperandswhosesizesaredifferent,decimal

arithmetic,andcomputationviatablelook-up.

Byfar,themostextensivesubjectthischaptercoversismultiprecision

arithmetic.Bytheconclusionofthischapteryouwillknowhowtoapply

arithmeticandlogicaloperationstointegeroperandsofanysize.Ifyou

needtoworkwithintegervaluesoutsidetherange±2billion(orwith

unsignedvaluesbeyond4billion),nosweat;thischapterwillshowyou

howtogetthejobdone.

Operandswhosesizesarenotthesamealsopresentsomespecial

problemsinarithmeticoperations.Forexample,youmaywanttoadda

128-bitunsignedintegertoa256-bitsignedintegervalue.Thischapter

discusseshowtoconvertthesetwooperandstoacompatibleformatso

theoperationmayproceed.

Thischapteralsodiscussesdecimalarithmeticusingthebinarycoded

decimal(BCD)featuresofthe80x86instructionsetandtheFPU.This

letsyouusedecimalarithmeticinthosefewapplicationsthatabsolutely

requirebase10operations(ratherthanbinary).

Finally,thischapterconcludesbydiscussingtheuseoftablestospeed

upcomplexcomputations.



9.2MultiprecisionOperations

Onebigadvantageofassemblylanguageoverhighlevellanguagesis

thatassemblylanguagedoesnotlimitthesizeofintegeroperations.For

example,thestandardCprogramminglanguagedefinesthreedifferent

integersizes:shortint,int,andlongint.[1]OnthePC,theseareoften16and32-bitintegers.Althoughthe80x86machineinstructionslimityouto

processing8-,16-,or32-bitintegerswithasingleinstruction,youcan

alwaysusemorethanoneinstructiontoprocessintegersofanysizeyou

desire.Ifyouwanttoadd256-bitintegervaluestogether,noproblem;it's

relativelyeasytoaccomplishthisinassemblylanguage.Thefollowing

sectionsdescribehowextendedvariousarithmeticandlogicaloperations

from16or32bitstoasmanybitsasyouplease.



9.2.1HLAStandardLibrarySupportforExtendedPrecision

Operations

Althoughitisimportantforyoutounderstandhowtodoextended

precisionarithmeticyourself,youshouldnotethattheHLAStandard

Libraryprovidesafullsetof64-bitand128-bitarithmeticandlogical

functionsthatyoucanuse.Theseroutinesareverygeneralpurposeand

areveryconvenienttouse.ThissectionwillbrieflydescribetheHLA

StandardLibrarysupportforextendedprecisionarithmetic.

Asnotedinearlierchapters,theHLAcompilersupportsseveraldifferent

64-bitand128-bitdatatypes.Asareview,herearetheextendeddata

typesthatHLAsupports:

uns64:64-bitunsignedintegers

int64:64-bitsignedintegers

qword:64-bituntypedvalues

uns128:128-bitunsignedintegers

int128:128-bitsignedintegers



lword:128-bituntypedvalues

HLAalsoprovidesatbytetype,butwewillnotconsiderthathere(see

thesectionondecimalarithmeticlaterinthischapter).

HLAletsyoucreateconstants,types,andvariableswhosetypeisoneof

theabove.HLAfullysupports64-bitand128-bitliteralconstantsand

constantarithmetic.Thisallowsyoutoinitialize64-and128-bitstatic

objectsusingstandarddecimal,hexadecimal,orbinarynotation.For

example:

static

u128:uns128:=123456789012345678901233567890;

i64:int64:=-12345678901234567890;

lw:lword:=$1234_5678_90ab_cdef_0000_ffff;

Ofcourse,the80x86generalpurposeintegerregistersdon'tsupport64bitor128-bitoperands,soyoumaynotdirectlymanipulatethesevalues

withsingle80x86machineinstructions(thoughyou'llseehowtodothis

withmultipleinstructionsstartinginthenextsection).

Inordertoeasilymanipulate64-bitand128-bitvalues,theHLAStandard

Library'smath.hhfmoduleprovidesasetoffunctionsthathandlemostof

thestandardarithmeticandlogicaloperationsyou'llneed.Youusethese

functionsinamannerquitesimilartothestandard32-bitarithmeticand

logicalinstructions.Forexample,considerthemath.addq(qword)and

math.addl(lword)functions:

math.addq(left64,right64,dest64);

math.addl(left128,right128,dest128);



Thesefunctionscomputethefollowing:

dest64:=left64+right64;//dest64,left64,andright64

//mustbe8-byteoperands

dest128:=left128+right128;//dest128,left128,andright12

//mustbe16-byteoperands

Thesefunctionsalsoleaveallthe80x86flagssetthesamewayyou'd

expectthemaftertheexecutionofanaddinstruction.Specifically,these



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

5 ISAM (Indexed Sequential Access Method) Files

Tải bản đầy đủ ngay(0 tr)

×