Skip to content

Instantly share code, notes, and snippets.

@robince
Created July 28, 2015 10:25
Show Gist options
  • Save robince/56a5b25f75953b81f24d to your computer and use it in GitHub Desktop.
Save robince/56a5b25f75953b81f24d to your computer and use it in GitHub Desktop.
module class_ExtendArray
implicit none
private
type, public :: ExtendArray
integer(8) :: capacity
integer(8) :: length
real(8), pointer :: data(:)
real(8), pointer :: buffer(:)
contains
procedure :: init => ea_init
procedure :: append => ea_append
final :: ea_deallocate
end type ExtendArray
contains
subroutine ea_init(this, capacity)
class(ExtendArray) :: this
integer(8), optional :: capacity
if (.not. present(capacity) ) capacity = 32
! allocate buffer
allocate(this%buffer(capacity))
this%capacity = capacity
this%length = 0
this%data => this%buffer(1:1)
end subroutine ea_init
subroutine ea_append(this, val)
class(ExtendArray) :: this
real(8), intent(in) :: val
integer(8) :: new_length
real(8), pointer :: newbuffer(:)
integer(8) :: new_capacity
new_length = this%length + 1
if( new_length .gt. this%capacity ) then
! reallocate and copy
new_capacity = 2*this%capacity
allocate(newbuffer(new_capacity))
newbuffer(1:this%capacity) = this%buffer
deallocate(this%buffer)
this%buffer => newbuffer
this%capacity = new_capacity
endif
this%data => this%buffer(1:new_length)
this%length = new_length
this%data(new_length) = val
end subroutine ea_append
subroutine ea_deallocate(this)
type(ExtendArray) :: this
nullify(this%data)
deallocate(this%buffer)
end subroutine ea_deallocate
end module class_ExtendArray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment