Base64 Encoding in Co-array Fortran

Our program demonstrates base64 encoding and decoding in Co-array Fortran. Here’s the full source code:

program base64_encoding
  use iso_fortran_env
  use base64_mod
  implicit none

  character(len=19) :: data = "abc123!?$*&()'-=@~"
  character(len=:), allocatable :: sEnc, sDec, uEnc, uDec

  ! Standard base64 encoding
  sEnc = encode_base64(data)
  print *, sEnc

  ! Standard base64 decoding
  sDec = decode_base64(sEnc)
  print *, sDec
  print *

  ! URL-safe base64 encoding
  uEnc = encode_base64_url(data)
  print *, uEnc

  ! URL-safe base64 decoding
  uDec = decode_base64_url(uEnc)
  print *, uDec

end program base64_encoding

In this example, we’re using a hypothetical base64_mod module that provides base64 encoding and decoding functionality. Co-array Fortran doesn’t have built-in support for base64, so we assume the existence of this module.

The program starts by defining a string that we’ll encode and decode.

We then use the encode_base64 function to perform standard base64 encoding. The encoded string is stored in sEnc and then printed.

For decoding, we use the decode_base64 function. The result is stored in sDec and printed. In a real-world scenario, you might want to check for decoding errors.

We repeat the process for URL-safe base64 encoding and decoding using encode_base64_url and decode_base64_url functions.

To run the program, save it as base64_encoding.f90 and compile it with your Co-array Fortran compiler. For example:

$ caf base64_encoding.f90 -o base64_encoding
$ ./base64_encoding

The output should look similar to this:

YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

Note that the standard and URL-safe encodings differ slightly (trailing + vs -), but both decode to the original string as expected.

Remember, this example assumes the existence of a base64_mod module. In practice, you might need to implement base64 encoding and decoding yourself or use a third-party library, as Co-array Fortran doesn’t provide built-in base64 support.