module m_psml_strings_helpers
  !
  ! A safe (re)allocator for character variables that will work even
  ! if compiler flags such as -fno-realloc-lhs are used
  !
  ! Rationale:
  !
  ! Allocatable character variables are a great addition to the
  ! language, but the automatic allocation feature (e.g. ' string =
  ! "Mary had a lamb"') might be inhibited if the compiler is told to
  ! avoid these kinds of allocations (for example, for performance
  ! reasons)
  !
  ! call safe_str_assign(string,"Mary had a lamb")
  !
  ! will work, and so will
  !
  ! call safe_str_assign(string, string // " in the farm")
  !
  ! The second argument is handled correctly by the compiler without any attempt
  ! at allocation, and treated as a character variable with the proper length.
  !
  ! NOTE: The 'len' intrinsic (and not 'len_trim') is used below for generality.
  
  public :: safe_str_assign

CONTAINS
  
  subroutine safe_str_assign(a,val)
    character(len=:), allocatable :: a
    character(len=*) :: val

    integer :: size
    
    size = len(val)
    if (allocated(a)) deallocate(a)
    allocate(character(size) :: a)
    a = val
    
  end subroutine safe_str_assign

end module m_psml_strings_helpers

