| 1 | using System; |
| 2 | using System.Text; |
| 3 | |
| 4 | namespace GodotTools.IdeMessaging |
| 5 | { |
| 6 | public class MessageDecoder |
| 7 | { |
| 8 | private class DecodedMessage |
| 9 | { |
| 10 | public MessageKind? Kind; |
| 11 | public string? Id; |
| 12 | public MessageStatus? Status; |
| 13 | public readonly StringBuilder Body = new StringBuilder(); |
| 14 | public uint? PendingBodyLines; |
| 15 | |
| 16 | public void Clear() |
| 17 | { |
| 18 | Kind = null; |
| 19 | Id = null; |
| 20 | Status = null; |
| 21 | Body.Clear(); |
| 22 | PendingBodyLines = null; |
| 23 | } |
| 24 | |
| 25 | public Message ToMessage() |
| 26 | { |
| 27 | if (!Kind.HasValue || Id == null || !Status.HasValue || |
| 28 | !PendingBodyLines.HasValue || PendingBodyLines.Value > 0) |
| 29 | throw new InvalidOperationException(); |
| 30 | |
| 31 | return new Message(Kind.Value, Id, new MessageContent(Status.Value, Body.ToString())); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | public enum State |
| 36 | { |
| 37 | Decoding, |
| 38 | Decoded, |
| 39 | Errored |
| 40 | } |
| 41 | |
| 42 | private readonly DecodedMessage decodingMessage = new DecodedMessage(); |
| 43 | |
| 44 | public State Decode(string messageLine, out Message? decodedMessage) |
| 45 | { |
| 46 | decodedMessage = null; |
| 47 | |
| 48 | if (!decodingMessage.Kind.HasValue) |
| 49 | { |
| 50 | if (!Enum.TryParse(messageLine, ignoreCase: true, out MessageKind kind)) |
| 51 | { |
| 52 | decodingMessage.Clear(); |
| 53 | return State.Errored; |
| 54 | } |
| 55 | |
| 56 | decodingMessage.Kind = kind; |
| 57 | } |
| 58 | else if (decodingMessage.Id == null) |
| 59 | { |
| 60 | decodingMessage.Id = messageLine; |
| 61 | } |
| 62 | else if (decodingMessage.Status == null) |
| 63 | { |
| 64 | if (!Enum.TryParse(messageLine, ignoreCase: true, out MessageStatus status)) |
| 65 | { |
| 66 | decodingMessage.Clear(); |
| 67 | return State.Errored; |
| 68 | } |
| 69 | |
| 70 | decodingMessage.Status = status; |
| 71 | } |
| 72 | else if (decodingMessage.PendingBodyLines == null) |
| 73 | { |
| 74 | if (!uint.TryParse(messageLine, out uint pendingBodyLines)) |
| 75 | { |
| 76 | decodingMessage.Clear(); |
| 77 | return State.Errored; |
| 78 | } |
| 79 | |
| 80 | decodingMessage.PendingBodyLines = pendingBodyLines; |
| 81 | } |
| 82 | else |
| 83 | { |
| 84 | if (decodingMessage.PendingBodyLines > 0) |
| 85 | { |
| 86 | decodingMessage.Body.AppendLine(messageLine); |
| 87 | decodingMessage.PendingBodyLines -= 1; |
| 88 | } |
| 89 | else |
| 90 | { |
| 91 | decodedMessage = decodingMessage.ToMessage(); |
| 92 | decodingMessage.Clear(); |
| 93 | return State.Decoded; |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | return State.Decoding; |
| 98 | } |
| 99 | } |
| 100 | } |