24 May 2011

Passing a Hash to a procedure (III)–Workaround

This part three in a series about the GFA-BASIC 32 Hash data type. In this part I discuss a workaround to use Hash procedure parameters and some peculiarities of the hash data type. However, you might like to read the previous posts first.
The workaround
A compiler bug blocks the the Hash Xxx commands for a Hash data type passed by-reference. On the other hand, the hash [ ] - operator syntax works well. The Hash Xxx commands work correctly for a local Hash data type, the one that is not passed as an argument to the procedure. The logical conclusion is to declare and use a temporary local Hash of the same data type and then somehow 'assign the hash parameter to the local hash'.
GFA-BASIC 32 has a two constructions to do just that:
  • Declaring a variable p As Pointer To data-type and than use Pointer(p) = address command to assign the pointer (<=> variable) an address.
  • Swapping the descriptors of the Hash variables: Swap hs1, hs2.
We can skip the first option. It should work but it doesn't, the compiler refuses the statement:
Dim hs As Pointer Hash Int
The swap method should work as well, but again it doesn't. The compiler doesn't know what to do with Swapping two Hash variables. However there is light at the end of the tunnel, Swap works for all other GFA-BASIC 32 data types including the UDT (Type). And that's the one we are going to use to Swap the hash variables, hence the procedure SwapHash().
Local hsInt As Hash Int
hashtest(HB[])

Proc hashtest(ByRef HS As Hash Int)
  Dim ths As Hash Int   ' temporary Hash
  SwapHash( *HS, *ths ) ' swap descriptors

  ' Now ONLY use ths[]
  Hash Add ths["dd"], 7
  ths ["aa"] = 8
  ' ...

  SwapHash( *HS, *ths ) ' swap back
EndProc

Proc SwapHash(ptrHash1%, ptrHash2%) Naked
  Local hsdesc1 As Pointer HashDesc
  Pointer(hsdesc1) = ptrHash1
  Local hsdesc2 As Pointer HashDesc
  Pointer(hsdesc2) = ptrHash2
  ' Make sure the types are the same:
  Assert hsdesc1.pType == hsdesc2.pType _
    ' SwapHash() - Hash type mismatch

  Swap hsdesc1, hsdesc2

  Type HashDesc         ' The Hash Descriptor
    pHashData As Long   ' pointer to memory
    pType As Long       ' Hash data type
  EndType
EndProc

No comments:

Post a Comment