| | 1 | | using System.Text.RegularExpressions; |
| | 2 | | using ValidateLib.ErrorsAndWarnings.Errors; |
| | 3 | | using ValidateLib.Metadata.Descriptors; |
| | 4 | |
|
| | 5 | | namespace ValidateLib.TabularData.Datatypes |
| | 6 | | { |
| | 7 | | public class HexBinaryDT : BaseDT, ILength |
| | 8 | | { |
| 1 | 9 | | public byte[]? Value { get; set; } |
| 1 | 10 | | public HexBinaryDT() { } |
| 1 | 11 | | public HexBinaryDT(string stringValue) : base(stringValue) |
| | 12 | | { |
| 1 | 13 | | CheckLexicalSpace(stringValue); |
| | 14 | | try |
| | 15 | | { |
| 1 | 16 | | Value = getValueFromString(stringValue); |
| 1 | 17 | | } |
| 1 | 18 | | catch (Exception) |
| | 19 | | { |
| 1 | 20 | | ErrorFactory.ThrowDatatypeValidationError(stringValue); |
| 0 | 21 | | } |
| 1 | 22 | | } |
| | 23 | |
|
| 0 | 24 | | public HexBinaryDT(string stringValue, FormatDescriptor format) : base(stringValue, format) |
| | 25 | | { |
| 0 | 26 | | CheckLexicalSpace(stringValue); |
| 0 | 27 | | MatchRegex(format.pattern!, stringValue); |
| | 28 | | try |
| | 29 | | { |
| 0 | 30 | | Value = getValueFromString(stringValue); |
| 0 | 31 | | } |
| 0 | 32 | | catch (Exception) |
| | 33 | | { |
| 0 | 34 | | ErrorFactory.ThrowDatatypeValidationError(stringValue); |
| 0 | 35 | | } |
| | 36 | |
|
| 0 | 37 | | } |
| | 38 | |
|
| | 39 | | void CheckLexicalSpace(string stringValue) |
| | 40 | | { |
| 1 | 41 | | string pattern = @"([0-9a-fA-F]{2})*"; |
| 1 | 42 | | if (!Regex.IsMatch(stringValue, pattern)) |
| 0 | 43 | | ErrorFactory.ThrowDatatypeValidationError(stringValue); |
| | 44 | |
|
| 1 | 45 | | } |
| | 46 | |
|
| | 47 | | byte[] getValueFromString(string stringValue) |
| | 48 | | { |
| 1 | 49 | | if (stringValue.Length % 2 != 0) |
| | 50 | | { |
| 1 | 51 | | throw new ArgumentException("Hex string must have an even number of characters."); |
| | 52 | | } |
| | 53 | |
|
| 1 | 54 | | byte[] byteArray = new byte[stringValue.Length / 2]; |
| | 55 | |
|
| 1 | 56 | | for (int i = 0; i < byteArray.Length; i++) |
| | 57 | | { |
| 1 | 58 | | byteArray[i] = Convert.ToByte(stringValue.Substring(i * 2, 2), 16); |
| | 59 | | } |
| | 60 | |
|
| 1 | 61 | | return byteArray; |
| | 62 | | } |
| | 63 | |
|
| | 64 | | public int Length() |
| | 65 | | { |
| 1 | 66 | | if (Value == null) return 0; |
| 1 | 67 | | return Value!.Count(); |
| | 68 | | } |
| | 69 | |
|
| | 70 | | public override bool IsPatternValid(FormatDescriptor format) |
| | 71 | | { |
| | 72 | | try |
| | 73 | | { |
| 0 | 74 | | Regex regex = new Regex(format.pattern!); |
| 0 | 75 | | return true; |
| | 76 | | } |
| 0 | 77 | | catch (Exception) |
| | 78 | | { |
| 0 | 79 | | return false; |
| | 80 | | } |
| 0 | 81 | | } |
| | 82 | | } |
| | 83 | | } |