//----------------------------------------------------------------------- // // Copyright (c) Outercurve Foundation. All rights reserved. // //----------------------------------------------------------------------- namespace DotNetOpenAuth.Messaging.Reflection { using System; using System.Diagnostics.Contracts; /// /// A pair of conversion functions to map some type to a string and back again. /// [ContractVerification(true)] internal struct ValueMapping { /// /// The mapping function that converts some custom type to a string. /// internal readonly Func ValueToString; /// /// The mapping function that converts some custom type to the original string /// (possibly non-normalized) that represents it. /// internal readonly Func ValueToOriginalString; /// /// The mapping function that converts a string to some custom type. /// internal readonly Func StringToValue; /// /// Initializes a new instance of the struct. /// /// The mapping function that converts some custom value to a string. /// The mapping function that converts some custom value to its original (non-normalized) string. May be null if the same as the function. /// The mapping function that converts a string to some custom value. internal ValueMapping(Func toString, Func toOriginalString, Func toValue) { Requires.NotNull(toString, "toString"); Requires.NotNull(toValue, "toValue"); this.ValueToString = toString; this.ValueToOriginalString = toOriginalString ?? toString; this.StringToValue = toValue; } /// /// Initializes a new instance of the struct. /// /// The encoder. internal ValueMapping(IMessagePartEncoder encoder) { Requires.NotNull(encoder, "encoder"); var nullEncoder = encoder as IMessagePartNullEncoder; string nullString = nullEncoder != null ? nullEncoder.EncodedNullValue : null; var originalStringEncoder = encoder as IMessagePartOriginalEncoder; Func originalStringEncode = encoder.Encode; if (originalStringEncoder != null) { originalStringEncode = originalStringEncoder.EncodeAsOriginalString; } this.ValueToString = obj => (obj != null) ? encoder.Encode(obj) : nullString; this.StringToValue = str => (str != null) ? encoder.Decode(str) : null; this.ValueToOriginalString = obj => (obj != null) ? originalStringEncode(obj) : nullString; } } }