Skip to content

Commit

Permalink
Implement encode and decode invocations
Browse files Browse the repository at this point in the history
  • Loading branch information
atuonufure committed Aug 15, 2023
1 parent 5f4493a commit def4eb5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
4 changes: 3 additions & 1 deletion fhirpathpy/engine/invocations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,12 @@
"nullable_input": True,
},
"length": {"fn": strings.length, "nullable_input": True},
"toChars": {"fn": strings.toChars },
"toChars": {"fn": strings.toChars},
"join": {"fn": strings.join, "arity": {0: [], 1: ["String"]}},
"split": {"fn": strings.split, "arity": {1: ["String"]}, "nullable_input": True},
"trim": {"fn": strings.trim, "nullable_input": True},
"encode": {"fn": strings.encode, "arity": {1: ["String"]}},
"decode": {"fn": strings.decode, "arity": {1: ["String"]}},
"abs": {"fn": math.abs},
"ceiling": {"fn": math.ceiling},
"exp": {"fn": math.exp},
Expand Down
47 changes: 47 additions & 0 deletions fhirpathpy/engine/invocations/strings.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import base64
import re
import fhirpathpy.engine.util as util

Expand Down Expand Up @@ -63,6 +64,52 @@ def trim(ctx, coll):
return string.strip()


def encode(ctx, coll, format):
if not coll:
return []

str_to_encode = coll[0] if isinstance(coll, list) else coll
if not str_to_encode:
return []

if format in ["urlbase64", "base64url"]:
encoded = base64.b64encode(str_to_encode.encode()).decode()
return encoded.replace("+", "-").replace("/", "_")

if format == "base64":
return base64.b64encode(str_to_encode.encode()).decode()

if format == "hex":
return "".join([hex(ord(c))[2:].zfill(2) for c in str_to_encode])

return []


def decode(ctx, coll, format):
if not coll:
return []

str_to_decode = coll[0] if isinstance(coll, list) else coll
if not str_to_decode:
return []

if format in ["urlbase64", "base64url"]:
decoded = str_to_decode.replace("-", "+").replace("_", "/")
return base64.b64decode(decoded).decode()

if format == "base64":
return base64.b64decode(str_to_decode).decode()

if format == "hex":
if len(str_to_decode) % 2 != 0:
raise ValueError("Decode 'hex' requires an even number of characters.")
return "".join(
[chr(int(str_to_decode[i : i + 2], 16)) for i in range(0, len(str_to_decode), 2)]
)

return []


def join(ctx, coll, separator=""):
stringValues = []
for n in coll:
Expand Down

0 comments on commit def4eb5

Please sign in to comment.