diff --git a/src/Input.jl b/src/Input.jl index cd683dd..aa50313 100644 --- a/src/Input.jl +++ b/src/Input.jl @@ -643,4 +643,30 @@ function inputSettings(settingsDirectory::String) return settings end # function inputSettings +""" + getEnum(string, enum_type) + +Converts a string to an enumerated type. +But only if the string matches an enumerated value. + +# Example +```jldoctest +julia> @enum trainTypes passenger freight + +julia> myTrain = "passenger" +"passenger" + +julia> myTrainType = getEnum(myTrain, trainTypes) +passenger::trainTypes = 0 +``` +""" +function getEnum(string::String, enum_type::DataType) + inst = instances(enum_type) # get all instances of enumerated type + syms = Symbol.(inst) # convert all instances to Symbols + lookup = Dict(zip(syms, inst)) # combine instances and Symbols in a lookup table + # + n_str = Symbol(string) # normalize String via a Symbol + return lookup[n_str] # return matched enumerated type +end # function getEnum + end # module Input diff --git a/test/testEnums.jl b/test/testEnums.jl new file mode 100644 index 0000000..e7d3cce --- /dev/null +++ b/test/testEnums.jl @@ -0,0 +1,24 @@ +#!/usr/bin/env julia +# -*- coding: UTF-8 -*- +# __julia-version__ = 1.7.0 +# __author__ = "Martin Scheidt" +# __copyright__ = "2021" +# __license__ = "ISC" + +include("../src/types.jl") +include("../src/Input.jl") + +using .Input +using YAML, Test + +@enum trainTypes passenger=1 freight=2 motorCoachTrain=3 + +@test Input.getEnum("passenger", trainTypes) == passenger::trainTypes +@test Input.getEnum("freight", trainTypes) == freight::trainTypes +@test Input.getEnum("motorCoachTrain", trainTypes) == motorCoachTrain::trainTypes + +data = YAML.load(open("data/trains/train_passenger_IC2.yaml")) +@test Input.getEnum(data["train"]["trainType"], trainTypes) == passenger::trainTypes + +data = YAML.load(open("data/trains/train_freight_V90withOreConsist.yaml")) +@test Input.getEnum(data["train"]["trainType"], trainTypes) == freight::trainTypes \ No newline at end of file