Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Single linked list unit

This code is a simple pascal library to handle single-linked-lists

function llsGetItem(id: cardinal; var start: pointer): pointer;

Returns an item of specified ID, it remains in list

function llsTakeOutItem(id: cardinal; var start: pointer): pointer;

Returns an item of specified ID, it is removed from list

procedure llsInsertItem(item: pointer; var start: pointer);

Inserts an item to list(item is a valid header)

function llsGetItemCount(start: pointer): cardinal;

Gets number of items

function llsNewSLLHeader: PSLLItem;

Allocates list item header

procedure llsKillSLLHeader(hdr: pointer);

Deallocated list item header
unit SLLMan;
interface
type
  PSLLItem = ^TSLLItem;
  TSLLItem = record
    Next: pointer;
    Data: pointer;
   end;

function llsGetItem(id: cardinal; var start: pointer): pointer;
function llsTakeOutItem(id: cardinal; var start: pointer): pointer;
procedure llsInsertItem(item: pointer; var start: pointer);
function llsGetItemCount(start: pointer): cardinal;
function llsNewSLLHeader: PSLLItem;
procedure llsKillSLLHeader(hdr: pointer);
       // These ids are numbered from 0
implementation
function malloc(size: cardinal): pointer;
begin
  GetMem(result,size);
end;
function llsGetItemCount(start: pointer): cardinal;
var
  cur: PSLLItem;
  tmp: cardinal;
begin
  if start = nil then begin llsGetItemCount := 0; Exit; end;
  tmp := 1;  cur := start;
  while (cur^.Next <> nil) do
  begin
    Inc(tmp);
    cur := cur^.Next;
  end;
  llsGetItemCount := tmp;
end;
procedure llsKillSLLHeader(hdr: pointer);
begin
  if hdr = nil then Exit;
  Free(hdr);
end;
function llsNewSLLHeader: PSLLItem;
var
  tmp: PSLLItem;
begin
  tmp := malloc(sizeof(TSLLItem));
  tmp^.Next := nil;
  tmp^.Data := nil;
  llsNewSLLHeader := tmp;
end;
function llsGetItem(id: cardinal; var start: pointer): pointer;
var
  cur: PSLLItem;
begin
  if start = nil then begin llsGetItem := nil; Exit; end;
  cur := start;
  while (id<>0) do
  begin
    if cur^.Next <> nil then
        begin
          Dec(id);
          cur := cur^.Next;
        end else
        begin
          llsGetItem := nil;
          Exit;
        end;
  end;
  llsGetItem := cur;
end;

function llsTakeOutItem(id: cardinal; var start: pointer): pointer;
var
  tmp: PSLLItem;
  last: PSLLItem;
begin
  if start = nil then begin llsTakeOutItem := nil; Exit; end;
  if (id = 0) then
    begin
      tmp := start;
      if tmp^.Next = nil then start := nil else start := tmp^.Next;
      llsTakeOutItem := tmp;
      Exit;
    end;
  tmp := start;
  repeat
    dec(id);
    last := tmp;
    tmp := tmp^.Next;
  until (id = 0);
  last^.Next := tmp^.Next;
  llsTakeOutitem := tmp;
end;
procedure llsInsertItem(item: pointer; var start: pointer);
var
  cur: PSLLItem;
begin
 if start = nil then
  begin
    start := item;
    exit;
  end;
 cur := start;
 while (cur^.Next<>nil) do cur := cur^.Next;
 cur^.Next := item;
end;

end.

IsFloat, IsInteger

// asdasd


function IsInteger(S: String): Boolean;
begin
  try
    Result := True;
    StrToInt(S);
  except on E: EConvertError do
    Result := False;
  end;
end;

function IsFloat(S: String): Boolean;
begin
  try
    Result := True;
    StrToFloat(S);
  except on E: EConvertError do
    Result := False;
  end;
end;

Wave Plotter //Pascal Class

A wave plotter component that is able to draw sin, poly and squared lines, I used this in a osciloscope xD

I didn't liked this code, but the draw part (TWaveShape.paint) is looking cool, I used the same "X" coord to draw the 3 kinds of lines :)

I mean:

loop(x){
case waveType of
wtSin: y := lala;
wtPoly: y := lele;
wtSqr: y := lili;
end;
}

unit WavePlotter;

interface

uses
  forms, dialogs, SysUtils, Classes, Controls, Graphics;

const
  PI2 = PI * 2;

type
  TWaveType = ( wtSqr, wtPoly, wtSin );

  TWave = class( TPersistent )
  public
    waveType: TWaveType;
    color: TColor;
    offset: integer;
    frequency, amplitude, volts, interval, gain: extended;

    procedure AssignTo(Dest: TPersistent); override;
  end;

  TWaveShape = class( TGraphicControl )
  protected
    fWaves: TList;
    fBoxSize: integer;
    fLineColor: TColor;

    function getWave(const index: integer): TWave;
    procedure setBoxSize(const Value: integer);

    function getBackgroundColor: TColor;
    procedure setBackgroundColor(const Value: TColor);
    procedure setLineColor(const Value: TColor);

  public
    constructor create( AOwner: TComponent ); override;
    destructor destroy; override;

    procedure clear;
    procedure delete( const index: integer );

    function add: integer;

    property waves[ const index: integer]: TWave read GetWave;

  published
    procedure paint; override;
    property boxSize: integer read fBoxSize write setBoxSize;
    property backgroundColor: TColor read getBackgroundColor write setBackgroundColor;
    property lineColor: TColor read fLineColor write setLineColor;

    //inherited
    //property Canvas;
    property Align;
    property Anchors;
    property Constraints;
    property DragCursor;
    property DragKind;
    property DragMode;
    property Enabled;
    //property Font;
    property ParentColor;
    //property ParentFont;
    property ParentShowHint;
    property PopupMenu;
    property ShowHint;
    property Visible;
    property OnClick;
    property OnContextPopup;
    property OnDblClick;
    property OnDragDrop;
    property OnDragOver;
    property OnEndDock;
    property OnEndDrag;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnStartDock;
    property OnStartDrag;
  end;

implementation

function max( const a, b: integer ): integer;
begin
  if a > b then
    result := a
  else
    result := b;
end;

{ TWaveShape }

function TWaveShape.add: integer;
begin
  result := fWaves.add( TWave.Create );
end;

procedure TWaveShape.clear;
begin
  while fWaves.count > 0 do begin
    TWave( fWaves[0] ).free;
    fWaves.delete( 0 );
  end;
end;

constructor TWaveShape.create(AOwner: TComponent);
begin
  inherited;
  fWaves := TList.create;
  fLineColor := clGray;
  color := clBtnFace;
  fBoxSize := 50;
end;

procedure TWaveShape.delete(const index: integer);
begin
  if ( index > -1 ) and ( index < fWaves.count ) then begin
    TWave( fWaves[index] ).free;
    fWaves.delete( index );
  end;
end;

destructor TWaveShape.destroy;
begin
  fWaves.free;
  inherited;
end;

function TWaveShape.getBackgroundColor: TColor;
begin
  result := color;
end;

function TWaveShape.getWave(const index: integer): TWave;
begin
  result := nil;
  if ( index > -1 ) and ( index < fWaves.count ) then
    result := TWave( fWaves[ index ] );
end;

procedure TWaveShape.paint;
var
  k, x: integer;
  lastX, lastY: array of integer;
  y: extended;
begin
  if not enabled then
    exit;
  canvas.brush.color := color;
  canvas.fillRect( clientRect );

  setLength( lastY, fWaves.count );
  setLength( lastX, fWaves.count );
  for k := 0 to high( lastY ) do begin
    lastY[k] := clientHeight div 2 + waves[k].offset;
    lastX[k] := 0;
  end;

  for x := 0 to max( clientWidth, clientHeight ) do begin
    with canvas do begin
      pen.color := fLineColor;
      pen.width := 1;
      pen.style := psDot;

      if x mod fBoxSize = 0 then begin
        moveTo( 0, x + trunc( frac( clientHeight / 2 / fBoxSize ) * fBoxSize ) );
        lineTo( clientWidth, x + trunc( frac( clientHeight / 2 / fBoxSize ) * fBoxSize ) );

        moveTo( x, 0 );
        lineTo( x, clientHeight );
      end;

      for k := 0 to fWaves.count - 1 do begin
        with waves[k] do begin
          pen.color := color;
          pen.width := 1;
          pen.style := psSolid;

          y := pi*k + PI2 * x * interval / fBoxSize * frequency;

          case waveType of
            wtSin:
              y := sin( y );
            wtPoly: begin
              y := frac( y / PI2 );
              if y <= 0.25 then
                y := y / 0.25
              else if y <= 0.75 then
                y := ( -y + 0.5 ) / 0.25
              else
                y := ( y - 1 ) / 0.25;
            end;
            wtSqr: begin
              if frac( y / PI2 ) <= 0.5 then
                y := 1
              else
                y := -1;
            end;
          end;
          y := ( y * ( fBoxSize / volts ) * amplitude * gain ) + clientHeight / 2 + offset;
          moveTo( lastX[k], lastY[k] );
          lastX[k] := x;
          lastY[k] := trunc( y );
          lineTo( x, lastY[k] );
        end;
      end;
    end;
  end;
end;

procedure TWaveShape.setBackgroundColor(const Value: TColor);
begin
  color := Value;
  Invalidate;
end;

procedure TWaveShape.setBoxSize(const Value: integer);
begin
  fBoxSize := Value;
  invalidate;
end;


procedure TWaveShape.setLineColor(const Value: TColor);
begin
  fLineColor := Value;
  Invalidate;
end;

{ TWave }

procedure TWave.AssignTo(Dest: TPersistent);
begin
  if Dest.ClassType <> TWave then
    inherited;
  with TWave( Dest ) do begin
    waveType := self.waveType;
    color := self.color;
    offset := self.offset;
    frequency := self.frequency;
    amplitude := self.amplitude;
    volts := self.volts;
    interval := self.interval;
    gain := self.gain;
  end;
end;

end.

Simple Stack //Pascal Class

A simple pointer stack...

unit Stack;

interface

uses
  SysUtils, Classes;

type
  TStack = class
  private
    FList: PPointerList;
    FCapacity, FCount: Cardinal;
    procedure Grow;
  public
    destructor Destroy; override;
    procedure Push( const Data: Pointer );
    function Pop: Pointer;
  end;

implementation

{ TStack }

destructor TStack.Destroy;
begin
  FreeMem( FList );
  inherited;
end;

procedure TStack.Grow;
begin
  if FCapacity > 64 then
    Inc( FCapacity, FCapacity div 4 )
  else
    if FCapacity > 8 then
      Inc( FCapacity, 16 )
    else
      Inc( FCapacity, 4 );
  ReallocMem( FList, FCapacity * SizeOf( Pointer ) );
end;

function TStack.Pop: Pointer;
begin
  if FCount > 0 then
  begin
    Dec( FCount );
    Result := FList^[FCount];
  end
  else
    Result := nil;
end;

procedure TStack.Push(const Data: Pointer);
begin
  if FCapacity = FCount then
    Grow;
  FList^[FCount] := Data;
  Inc( FCount );
end;

end.

Fast Sequential Search/Replace Engine supporting wildcards, backward search, whole words, etc... //Pascal Class

A quite fast unit to search/replace strings sequentially (while Seeker.Search() do...) in files/strings done mostly with pointers to improve speed. It's able to search backward, count end of lines, check case-sensitiveness, match whole words and handle wildcards (* and ?),

The search method was divided into 4 specialized methods, again to improve speed. The right method is choosed according to the options that were setted (wildcard, search backward, etc...)

This is an old code that doesn't match my current skills, anyway it has some cool techniques that I really enjoyed :)

//
//    TNotesSeeker - classe de buscas do Notes.
//
//    Notes, http://notes.codigolivre.org.br
//    Copyright (C) 2003-2004, Equipe do Notes.
//
//    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; either version 2 of the License, or
//    (at your option) any later version.
//
//    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
//
//    **************************************************************
//    Revision #0
//      Version  : 1.0.0
//      Date     : 2003-11-30 22:00:00 GMT -3:00
//      Reviewer : Jonas Raoni Soares Silva
//      Changes  : Criada a classe.
//    **************************************************************
//    Revision #1
//      Version  : 1.0.1
//      Date     : 2004-09-09 03:30:00 GMT -3:00
//      Reviewer : Jonas Raoni Soares Silva
//      Changes  : Acho q acabaram-se os bugs... Será??? :]
//    **************************************************************

(*
@abstract(NotesSeeker - classe de buscas do Notes.)
@author(Jonas Raoni Soares Silva <jonblackjack@bol.com.br>)
@created(30 Nov 2003)
*)

unit NotesSeeker;

interface

uses
  SysUtils, Classes;

type

{
  @code(ENotesSeekerException) -
    Notificar erros na classe TNotesSeeker de forma
    profissional, facilitando a interceptação e/ou log de
    erros
}
  ENotesSeekerException = class ( Exception )
  public
    constructor Create(const Msg: string);
    constructor CreateFmt(const Msg: string; const Args: array of const);
  end;

  {Opões de pesquisa: <BR>
   @code(nsHandleEOL) - se você precisar buscar por quebras de linhas, você precisa setar esta opção.<BR>
   @code(nsCaseSensitive) - diferenciar maiúsculas de minúsculas.<BR>
   @code(nsWholeWords) - retorna apenas palavras inteiras.<BR>
   @code(nsBackward) - busca de traz para frente. <BR>
   @code(nsHandleWildCard) - usa coringas * e ? na pesquisa.}
  TNotesSeekerOption = ( nsHandleEOL, nsCaseSensitive, nsWholeWords, nsBackward, nsHandleWildCard );
  { Set de @link(TNotesSeekerOption).}
  TNotesSeekerOptions = set of TNotesSeekerOption;

  TSearchFunction = function: Boolean of object;

{
  @code(TNotesSeeker) -
    Permite fazer buscas em strings com várias opções
}
  TNotesSeeker = class(TObject)
  private
    Jump, LineJump: Cardinal;
    FList: TList;
  protected
    FMatches, FStartAt, FEOLLen, FSearchLen, FCurCol,
    FCurLine, FMatchLen, FMatchLine, FMatchCol: Cardinal;

    FBufferEnd, FBuffer, FBufferBegin, FBufferBackup,
    FEOL, FSearchBegin, FSearch, FSearchEnd: PChar;

    FOptions: TNotesSeekerOptions;

    FContextRightLenght, FContextLeftLenght: Cardinal;

    FKeepText: Boolean;

    function GetText: string;
    function GetReplacedText: string;
    function GetContext: string;
    function GetSearchStr: string;
    function GetRemainingText: string;
    function GetCurByte: Cardinal;
    function GetEOL: string;

    procedure SetOptions(const Value: TNotesSeekerOptions);
    procedure SetText( const Value: string);
    procedure SetSearchStr(const Value: string);
    procedure SetEOL(const Value: string);

    procedure FreeBuffer;
    procedure FreeEOL;
    procedure FreeSearchStr;

    {Search Engines}
    function SearchForward: Boolean;
    function SearchForwardWithWildCard: Boolean;
    function SearchBackward: Boolean;
    function SearchBackwardWithWildCard: Boolean;

  public
    { Efetua a busca: se o termo procurado for encontrado, retorna true, caso contrário retorna false }
    Search: TSearchFunction;

    { Método construtor }
    constructor Create; virtual;
    { Método destruidor }
    destructor Destroy; override;

    { Armazena o tamanho do "match", quando a opção wildcard estiver desligada esta será igual ao tamanho da própria string procurada }
    property MatchLength: Cardinal read FMatchLen;
    { Quando HandleEOL fizer parte das opções, armazenará a linha onde a string procurada foi encontrada }
    property CurLine: Cardinal read FMatchLine;
    { Armazenará a coluna onde a string procurada foi encontrada, se HandleEOL não estiver nas opções, armazenará a mesma coisa que a propriedade CurByte }
    property CurCol: Cardinal read FMatchCol;
    { Armazena a posição ou byte "absoluto" onde a string foi encontrada }
    property CurByte: Cardinal read GetCurByte;
    { Especifica a posição/byte inicial onde a busca deverá começar }
    property StartAt: Cardinal read FStartAt write FStartAt;
    { Retorna o contexto onde a string procurada foi encontrada }
    property Context: string read GetContext;
    { Especifica a quantidade de caracteres que deverão fazer parte do contexto encontrado ao lado esquerdo da string procurada }
    property ContextLeftLenght: Cardinal read FContextLeftLenght write FContextLeftLenght;
    { Especifica a quantidade de caracteres que deverão fazer parte do contexto encontrado ao lado direito da string procurada }
    property ContextRightLenght: Cardinal read FContextRightLenght write FContextRightLenght;
    { Armazena o número de strings que coincidiram com a busca até o presente momento }
    property Matches: Cardinal read FMatches;
    { Permite alterar a sequência de caracteres que demarcam o fim de uma linha }
    property EOL: string read GetEOL write SetEOL;
    { Armazena as opções atualmente habilitadas para a busca, podendo ser alterada a qualquer momento }
    property Options: TNotesSeekerOptions read FOptions write SetOptions;
    { Termo a ser procurado no texto }
    property SearchStr: string read GetSearchStr write SetSearchStr;
    { Texto onde a busca será efetuada }
    property Text: string read GetText write SetText;
    { Texto restante ao término da busca }
    property RemainingText: string read GetRemainingText;
    { Especifica se a classe deverá manter uma cópia do texto setado inicialmente }
    property KeepText: Boolean read FKeepText write FKeepText;
    { Retorna o texto com os replaces, caso KeepText seja falso, essa propriedade se torna sinônimo da propriedade Text }
    property ReplacedText: string read GetReplacedText;

    { Prepara tudo para uma nova busca }
    procedure StartSearch;
    { Carrega o texto da busca a partir de um arquivo }
    procedure LoadFromFile( const AFilename: string );
    { Carrega o texto da busca a partir de um stream }
    procedure LoadFromStream( const AStream: TStream );
    { Carrega o texto da busca a partir de um buffer }
    procedure LoadFromBuffer( const ABuffer: PChar );
    { Efetua a substituição da string encontrada pela string contida em "S" }
    procedure Replace( const S: String );
    { Modo prático para setar as opções }
    procedure EnableOptions( const CaseSensitive: Boolean = true; const WholeWords: Boolean = false; const HandleEOL: Boolean = true; const HandleWildCard: Boolean = false; const Backward: Boolean = false );

  end;

  { Compara Str1 e Str2 de trás pra frente, se as duas forem iguais retorna true, caso contrário false }
  function StrLRComp( S1, S2: PChar; const S2Begin: PChar ): Boolean;
  { Converte para maiúsculo (ANSI) -> VALEUUUUU TIO RUSSÃO hahaha, o que tem no delphi "aplica a alteração"
    Idéia de manter tabela com tudo maiúsculo arrancada de "QStrings 6.07.424 Copyright (C) 2000, 2003 Andrew Dryazgov [ andrewdr@newmail.ru ]" }
  function AnsiUpCase(Ch: Char): Char;

const
  { Caracteres que definem delimitadores de palavra, usada quando a opção WholeWords está ativa }
  WhiteSpaces: set of Char = [' ',#9,#13,#10,'!','"','#','$','%','&','''','(',')','*','+','-','/',':',';','<','=','>','?','@','[','\',']','^','`','{','|','}','~'];

const
  //fiz algumas alterações hehe, o tiozaum russo devia  começano a ficar cego enqto fazia isso :)
  ToUpperChars: array[0..255] of Char =
    (#$00,#$01,#$02,#$03,#$04,#$05,#$06,#$07,#$08,#$09,#$0A,#$0B,#$0C,#$0D,#$0E,#$0F,
     #$10,#$11,#$12,#$13,#$14,#$15,#$16,#$17,#$18,#$19,#$1A,#$1B,#$1C,#$1D,#$1E,#$1F,
     #$20,#$21,#$22,#$23,#$24,#$25,#$26,#$27,#$28,#$29,#$2A,#$2B,#$2C,#$2D,#$2E,#$2F,
     #$30,#$31,#$32,#$33,#$34,#$35,#$36,#$37,#$38,#$39,#$3A,#$3B,#$3C,#$3D,#$3E,#$3F,
     #$40,#$41,#$42,#$43,#$44,#$45,#$46,#$47,#$48,#$49,#$4A,#$4B,#$4C,#$4D,#$4E,#$4F,
     #$50,#$51,#$52,#$53,#$54,#$55,#$56,#$57,#$58,#$59,#$5A,#$5B,#$5C,#$5D,#$5E,#$5F,
     #$60,#$41,#$42,#$43,#$44,#$45,#$46,#$47,#$48,#$49,#$4A,#$4B,#$4C,#$4D,#$4E,#$4F,
     #$50,#$51,#$52,#$53,#$54,#$55,#$56,#$57,#$58,#$59,#$5A,#$7B,#$7C,#$7D,#$7E,#$7F,
     #$80,#$81,#$82,#$81,#$84,#$85,#$86,#$87,#$88,#$89,#$8A,#$8B,#$8C,#$8D,#$8E,#$8F,
     #$90,#$91,#$92,#$93,#$94,#$95,#$96,#$97,#$98,#$99,#$8A,#$9B,#$8C,#$9D,#$9E,#$9F,
     #$A0,#$A1,#$A1,#$A3,#$A4,#$A5,#$A6,#$A7,#$A8,#$A9,#$AA,#$AB,#$AC,#$AD,#$AE,#$AF,
     #$B0,#$B1,#$B2,#$B2,#$A5,#$B5,#$B6,#$B7,#$A8,#$B9,#$BA,#$BB,#$BC,#$BD,#$BE,#$BF,
     #$C0,#$C1,#$C2,#$C3,#$C4,#$C5,#$C6,#$C7,#$C8,#$C9,#$CA,#$CB,#$CC,#$CD,#$CE,#$CF,
     #$D0,#$D1,#$D2,#$D3,#$D4,#$D5,#$D6,#$D7,#$D8,#$D9,#$DA,#$DB,#$DC,#$DD,#$DE,#$DF,
     #$C0,#$C1,#$C2,#$C3,#$C4,#$C5,#$C6,#$C7,#$C8,#$C9,#$CA,#$CB,#$CC,#$CD,#$CE,#$CF,
     #$D0,#$D1,#$D2,#$D3,#$D4,#$D5,#$D6,#$F7,#$D8,#$D9,#$DA,#$DB,#$DC,#$DD,#$DE,#$9F);

implementation

function StrLRComp( S1, S2: PChar; const S2Begin: PChar ): Boolean;
begin
  while ( S2 <> S2Begin ) and ( S1^ = S2^ ) do begin
    dec( S1 );
    dec( S2 );
  end;
  Result := ( S1^ = S2^ ) and ( S2 = S2Begin );
end;

function AnsiUpCase(Ch: Char): Char;
begin
  Result := ToUpperChars[ ord( ch ) ];
end;


{ class : TNotesSeeker }

{ TNotesSeeker : protected }

function TNotesSeeker.GetText: string;
begin
  if Assigned( FBufferBackup ) then
    Result := StrPas( FBufferBackup )
  else
    Result := ReplacedText;
end;

function TNotesSeeker.GetReplacedText: string;
begin
  Result := StrPas( FBufferBegin );
end;

function TNotesSeeker.GetContext: string;
var
  BeginAt, EndAt: PChar;
begin
  if not ( nsBackward in FOptions ) then begin
    BeginAt := FBuffer - FMatchLen - FContextLeftLenght;
    EndAt := FBuffer+FContextRightLenght;
  end
  else begin
    BeginAt := FBuffer+<