⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 uhashtable.pas

📁 楠楠写的DBiocp例子都是源码
💻 PAS
字号:
unit uHashTable;

interface

uses
  Windows, SysUtils;

type

  PPHashItem = ^PHashItem;
  PHashItem = ^THashItem;
  THashItem = record
    Next: PHashItem;
    Key: string;
    Value: TObject;
  end;

  THashTable = class
  private
    Buckets: array of PHashItem;
  protected
    function Find(const Key: string): PPHashItem;
    function HashOf(const Key: string): Cardinal; virtual;
  public
    constructor Create;
    procedure SetSize(Size: Integer = 256);
    destructor Destroy; override;
    procedure Put(const Key: string; AObject: TObject);
    procedure Clear;
    procedure Remove(const Key: string);
    function Modify(const Key: string; AObject: TObject): Boolean;
    function Get(const Key: string): TObject;
  end;

implementation
 
constructor THashTable.Create;
begin
  inherited Create;
end;

destructor THashTable.Destroy;
begin
  Clear;
  inherited Destroy;
end;

procedure THashTable.SetSize(Size: Integer);
begin
  SetLength(Buckets, Size);
end;

procedure THashTable.Put(const Key: string; AObject: TObject);
var
  Hash: Integer;
  Bucket: PHashItem;
begin
  Hash := HashOf(Key) mod Cardinal(Length(Buckets));
  New(Bucket);
  Bucket^.Key := Key;
  Bucket^.Value := AObject;
  Bucket^.Next := Buckets[Hash];
  Buckets[Hash] := Bucket;
end;

procedure THashTable.Clear;
var
  I: Integer;
  P, N: PHashItem;
begin
  for I := 0 to Length(Buckets) - 1 do
  begin
    P := Buckets[I];
    while P <> nil do
    begin
      N := P^.Next;
      if Assigned(P^.Value) then FreeAndNil(P^.Value);
      dispose(P);
      P := N;
    end;
    Buckets[I] := nil;
  end;
end;

function THashTable.Find(const Key: string): PPHashItem;
var
  Hash: Integer;
begin
  Hash := HashOf(Key) mod Cardinal(Length(Buckets));
  Result := @Buckets[Hash];
  while Result^ <> nil do
  begin
  if Result^.Key = Key then
    Exit
  else
    Result := @Result^.Next;
  end;
end;
   
function THashTable.HashOf(const Key: string): Cardinal;
var
  I: Integer;
begin
  Result := 0;
  for I := 1 to Length(Key) do
  Result := ((Result shl 2) or (Result shr (SizeOf(Result) * 8 - 2))) xor
    Ord(Key[I]);
end;
   
function THashTable.Modify(const Key: string; AObject: TObject): Boolean;
var
  P: PHashItem;
begin
  P := Find(Key)^;
  if P <> nil then begin
    Result := True;
    P^.Value := AObject;
  end
  else
    Result := False;
end;
   
procedure THashTable.Remove(const Key: string);
var
  P: PHashItem;
  Prev: PPHashItem;
begin
  Prev := Find(Key);
  P := Prev^;
  if P <> nil then
  begin
    Prev^ := P^.Next;
    if Assigned(P^.Value) then FreeAndNil(P^.Value);
    Dispose(P);
  end;
end;
   
function THashTable.Get(const Key: string): TObject;
var
  P: PHashItem;
begin
  P := Find(Key)^;
  if P <> nil then
    Result := P^.Value
  else
    Result := nil;
end;

end.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -