Created
April 4, 2020 13:41
-
-
Save denise-amiga/1904b525f21afd37c85fac3c5e1679e1 to your computer and use it in GitHub Desktop.
Simple generic list in freebasic using "any ptr" in the base class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type listBucket | |
payload as any ptr | |
nextBucket as listBucket ptr | |
end type | |
type List extends object | |
private: | |
_start as listBucket ptr | |
_end as listBucket ptr | |
_mutex as any ptr | |
_size as uinteger | |
public: | |
declare destructor() | |
declare Constructor() | |
declare sub AddItem(item as any ptr) | |
declare function GetItem(id as uinteger) as any ptr | |
declare property Size() as uinteger | |
end type | |
constructor List() | |
_mutex = MutexCreate() | |
_start = new ListBucket | |
_end = _start | |
end constructor | |
destructor List() | |
if _mutex <> 0 then mutexdestroy(_mutex) | |
end destructor | |
sub List.AddItem(item as any ptr) | |
' Initial list: | |
mutexlock(_mutex) | |
_end->payload = item | |
_end->nextBucket = new ListBucket | |
_end = _end->nextBucket | |
_size += 1 | |
mutexunlock(_mutex) | |
end sub | |
function List.GetItem(id as uinteger) as any ptr | |
' Error: | |
if ( id > _size ) then return 0 | |
' handle the fast and easy cases first: | |
if ( id = 0 ) then return _start->payload | |
if ( id = _size ) then return _end->payload | |
' Start with 1, because 0 is handled above. | |
dim i as integer = 1 | |
mutexlock(_mutex) | |
dim bucket as ListBucket ptr = _start->nextBucket | |
while ( i < id and bucket->NextBucket <> 0 ) | |
i+=1 | |
bucket = bucket->NextBucket | |
wend | |
mutexunlock(_mutex) | |
if ( i = id ) then | |
return bucket->Payload | |
else | |
return 0 | |
end if | |
end function | |
property List.Size() as uinteger | |
return this._size | |
end property | |
type IntegerList extends List | |
declare Function GetInt (id as uinteger) as integer | |
declare sub AddInt(item as integer) | |
end type | |
function IntegerList.GetInt(id as uinteger) as integer | |
dim result as any ptr = base.GetItem(id) | |
if ( result <> 0 ) then | |
return *cast(integer ptr, result) | |
else | |
return 0 | |
end if | |
end function | |
sub IntegerList.AddInt(item as integer) | |
dim as integer ptr newItem = callocate(sizeof(integer)) | |
*newItem = item | |
base.AddItem(newItem) | |
end sub | |
dim as IntegerList test | |
for i as integer = 1 to 100 | |
test.AddInt(i) | |
next | |
for i as integer = 0 to test.Size -1 | |
? test.GetInt(i) | |
next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment