├── .gitignore ├── LICENSE ├── README.md ├── bad ├── adexp.go ├── adexp_test.go ├── aftn.go ├── icao.go └── util.go ├── good ├── adexp.go ├── adexp_test.go ├── aftn.go ├── icao.go └── util.go └── resources └── tests └── adexp.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Good code vs Bad code in Golang -------------------------------------------------------------------------------- /bad/adexp.go: -------------------------------------------------------------------------------- 1 | package bad 2 | 3 | import ( 4 | "strings" 5 | "fmt" 6 | "regexp" 7 | "sync" 8 | ) 9 | 10 | const ( 11 | patternSubfield = "-.[^-]*" 12 | 13 | tokenTitle = "TITLE" 14 | tokenAdep = "ADEP" 15 | tokenAltnz = "ALTNZ" 16 | tokenAdes = "ADES" 17 | tokenArcid = "ARCID" 18 | tokenArctyp = "ARCTYP" 19 | tokenCeqpt = "CEQPT" 20 | tokenMsgtxt = "MSGTXT" 21 | tokenComment = "COMMENT" 22 | tokenEetfir = "EETFIR" 23 | tokenSpeed = "SPEED" 24 | tokenEstdata = "ESTDATA" 25 | tokenGeo = "GEO" 26 | tokenRtepts = "RTEPTS" 27 | 28 | subtokenPtid = "PTID" 29 | subtokenEto = "ETO" 30 | subtokenFl = "FL" 31 | subtokenGeoid = "GEOID" 32 | subtokenLattd = "LATTD" 33 | subtokenLongtd = "LONGTD" 34 | ) 35 | 36 | var ( 37 | stringNewline = "\n" 38 | stringNewlineDash = "\n-" 39 | stringBegin = "-BEGIN" 40 | stringEnd = "-END" 41 | stringEmpty = " " 42 | stringComment = "//" 43 | stringDash = "-" 44 | 45 | regexpSubfield, _ = regexp.Compile(patternSubfield) 46 | 47 | factory = map[string]func(string, string) interface{}{ 48 | tokenTitle: parseSimpleToken, 49 | tokenAdep: parseSimpleToken, 50 | tokenAltnz: parseSimpleToken, 51 | tokenAdes: parseSimpleToken, 52 | tokenArcid: parseSimpleToken, 53 | tokenArctyp: parseSimpleToken, 54 | tokenCeqpt: parseSimpleToken, 55 | tokenMsgtxt: parseSimpleToken, 56 | tokenComment: parseSimpleToken, 57 | 58 | tokenEetfir: parseSimpleToken, 59 | tokenSpeed: parseSimpleToken, 60 | 61 | tokenEstdata: parseComplexToken, 62 | tokenGeo: parseComplexToken, 63 | tokenRtepts: parseComplexToken, 64 | } 65 | 66 | mutexEetfir = &sync.RWMutex{} 67 | mutexSpeed = &sync.RWMutex{} 68 | mutexEstdata = &sync.RWMutex{} 69 | mutexGeo = &sync.RWMutex{} 70 | mutexRtepts = &sync.RWMutex{} 71 | ) 72 | 73 | func ParseAdexpMessage(string string) (Message, error) { 74 | preprocessed, _ := preprocess(string) 75 | message := process(preprocessed) 76 | 77 | return message, nil 78 | } 79 | 80 | func preprocess(in string) (string, error) { 81 | if len(in) == 0 { 82 | return "", fmt.Errorf("Input is empty") 83 | } 84 | 85 | lines := strings.Split(in, stringNewline) 86 | var result string 87 | 88 | for i := 0; i < len(lines); i++ { 89 | line := lines[i] 90 | if startWith(line, stringEnd) { 91 | } else if startWith(line, stringBegin) { 92 | trimed := strings.Trim(line, stringEmpty) 93 | result = result + stringNewlineDash + trimed[len(stringBegin)+1:] 94 | } else if startWith(line, stringDash) { 95 | result = result + stringNewline + strings.Trim(line, stringEmpty) 96 | } else if startWith(line, stringEmpty) { 97 | result = result + stringEmpty + strings.Trim(line, stringEmpty) 98 | } else { 99 | result = result + stringEmpty + strings.Trim(line, stringEmpty) 100 | } 101 | } 102 | 103 | return result, nil 104 | } 105 | 106 | func process(in string) Message { 107 | lines := strings.Split(in, stringNewline) 108 | 109 | ch := make(chan string, len(lines)) 110 | 111 | msg := Message{} 112 | 113 | for i := 0; i < len(lines); i++ { 114 | go mapLine(&msg, lines[i], ch) 115 | } 116 | 117 | for i := 0; i < len(lines); i++ { 118 | <-ch 119 | } 120 | 121 | msg.Type = AdexpType 122 | 123 | return msg 124 | } 125 | 126 | func mapLine(msg *Message, in string, ch chan string) { 127 | if !startWith(in, stringComment) { 128 | token, value := parseLine(in) 129 | if token != "" { 130 | f, contains := factory[string(token)] 131 | if !contains { 132 | ch <- "ok" 133 | } else { 134 | data := f(token, value) 135 | enrichMessage(msg, data) 136 | ch <- "ok" 137 | } 138 | } else { 139 | ch <- "ok" 140 | return 141 | } 142 | } else { 143 | ch <- "ok" 144 | return 145 | } 146 | } 147 | 148 | func enrichMessage(msg *Message, data interface{}) { 149 | if data == nil { 150 | return 151 | } 152 | 153 | switch data.(type) { 154 | case simpleToken: 155 | simpleToken := data.(simpleToken) 156 | value := simpleToken.value 157 | switch simpleToken.token { 158 | case tokenTitle: 159 | msg.Title = value 160 | case tokenAdep: 161 | msg.Adep = value 162 | case tokenAltnz: 163 | msg.Alternate = value 164 | case tokenAdes: 165 | msg.Ades = value 166 | case tokenArcid: 167 | msg.Arcid = value 168 | case tokenArctyp: 169 | msg.ArcType = value 170 | case tokenCeqpt: 171 | msg.Ceqpt = value 172 | case tokenMsgtxt: 173 | msg.MessageText = value 174 | case tokenComment: 175 | msg.Comment = value 176 | case tokenEetfir: 177 | mutexEetfir.Lock() 178 | msg.Eetfir = append(msg.Eetfir, value) 179 | mutexEetfir.Unlock() 180 | case tokenSpeed: 181 | mutexSpeed.Lock() 182 | msg.Speed = append(msg.Speed, value) 183 | mutexSpeed.Unlock() 184 | } 185 | case complexToken: 186 | complexToken := data.(complexToken) 187 | value := complexToken.value 188 | switch complexToken.token { 189 | case tokenEstdata: 190 | mutexEstdata.Lock() 191 | for _, v := range value { 192 | fl := extractFlightLevel(v[subtokenFl]) 193 | msg.Estdata = append(msg.Estdata, estdata{v[subtokenPtid], v[subtokenEto], fl}) 194 | } 195 | mutexEstdata.Unlock() 196 | case tokenGeo: 197 | mutexGeo.Lock() 198 | for _, v := range value { 199 | msg.Geo = append(msg.Geo, geo{v[subtokenGeoid], v[subtokenLattd], v[subtokenLongtd]}) 200 | } 201 | mutexGeo.Unlock() 202 | case tokenRtepts: 203 | mutexRtepts.Lock() 204 | for _, v := range value { 205 | fl := extractFlightLevel(v[subtokenFl]) 206 | msg.RoutePoints = append(msg.RoutePoints, rtepts{v[subtokenPtid], fl, v[subtokenEto]}) 207 | } 208 | mutexRtepts.Unlock() 209 | } 210 | } 211 | } 212 | 213 | func parseSimpleToken(token, value string) interface{} { 214 | return simpleToken{string(token), string(value)} 215 | } 216 | 217 | func parseComplexToken(token, value string) interface{} { 218 | if value == "" { 219 | return complexToken{string(token), nil} 220 | } 221 | 222 | v := parseComplexLines(value, make(map[string]string), nil) 223 | 224 | return complexToken{string(token), v} 225 | } 226 | 227 | func parseComplexLines(in string, currentMap map[string]string, out []map[string]string) []map[string]string { 228 | match := regexpSubfield.Find([]byte(in)) 229 | 230 | if match == nil { 231 | out = append(out, currentMap) 232 | return out 233 | } 234 | 235 | sub := string(match) 236 | 237 | h, l := parseLine(sub) 238 | 239 | _, contains := currentMap[string(h)] 240 | 241 | if contains { 242 | out = append(out, currentMap) 243 | currentMap = make(map[string]string) 244 | } 245 | 246 | currentMap[string(h)] = string(strings.Trim(l, stringEmpty)) 247 | 248 | return parseComplexLines(in[len(sub):], currentMap, out) 249 | } 250 | -------------------------------------------------------------------------------- /bad/adexp_test.go: -------------------------------------------------------------------------------- 1 | package bad 2 | 3 | import ( 4 | "io/ioutil" 5 | "testing" 6 | ) 7 | 8 | func BenchmarkParseAdexpMessage(t *testing.B) { 9 | bytes, _ := ioutil.ReadFile("../resources/tests/adexp.txt") 10 | 11 | for i := 0; i < t.N; i++ { 12 | ParseAdexpMessage(string(bytes)) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /bad/aftn.go: -------------------------------------------------------------------------------- 1 | package bad 2 | 3 | const ( 4 | AdexpType = 0 5 | IcaoType = 1 6 | ) 7 | 8 | const upperLevel = 350 9 | 10 | type estdata struct { 11 | Ptid string 12 | Eto string 13 | FlightLevel int 14 | } 15 | 16 | type geo struct { 17 | Geoid string 18 | Latitude string 19 | Longitude string 20 | } 21 | 22 | type rtepts struct { 23 | Ptid string 24 | FlightLevel int 25 | Eto string 26 | } 27 | 28 | type Message struct { 29 | Type int 30 | Title string 31 | Adep string 32 | Ades string 33 | Alternate string 34 | Arcid string 35 | ArcType string 36 | Ceqpt string 37 | MessageText string 38 | Comment string 39 | Eetfir []string 40 | Speed []string 41 | Estdata []estdata 42 | Geo []geo 43 | RoutePoints []rtepts 44 | } 45 | 46 | type simpleToken struct { 47 | token string 48 | value string 49 | } 50 | 51 | type complexToken struct { 52 | token string 53 | value []map[string]string 54 | } 55 | 56 | func IsUpperLevel(m Message) bool { 57 | for _, r := range m.RoutePoints { 58 | if r.FlightLevel > upperLevel { 59 | return true 60 | } 61 | } 62 | 63 | return false 64 | } 65 | -------------------------------------------------------------------------------- /bad/icao.go: -------------------------------------------------------------------------------- 1 | package bad 2 | 3 | func ParseIcaoMessage(bytes []byte) (Message, error) { 4 | // Do something 5 | 6 | return Message{Type: IcaoType}, nil 7 | } 8 | -------------------------------------------------------------------------------- /bad/util.go: -------------------------------------------------------------------------------- 1 | package bad 2 | 3 | import ( 4 | "strings" 5 | "strconv" 6 | ) 7 | 8 | func startWith(in, test string) bool { 9 | if len(test) > len(in) { 10 | return false 11 | } 12 | 13 | i := 0 14 | for range test { 15 | if test[i] != in[i] { 16 | return false 17 | } 18 | i++ 19 | } 20 | 21 | return true 22 | } 23 | 24 | func parseLine(in string) (string, string) { 25 | if len(in) == 0 { 26 | return "", "" 27 | } 28 | 29 | i := strings.Index(in, stringEmpty) 30 | 31 | if i == -1 { 32 | return in[1:], "" 33 | } 34 | 35 | return in[1:i], in[i+1:] 36 | } 37 | 38 | func extractFlightLevel(in string) int { 39 | fl, _ := strconv.Atoi(in[1:]) 40 | return fl 41 | } 42 | -------------------------------------------------------------------------------- /good/adexp.go: -------------------------------------------------------------------------------- 1 | package good 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | log "github.com/sirupsen/logrus" 8 | "regexp" 9 | ) 10 | 11 | const ( 12 | // Pattern to parse subfields in a complex token 13 | patternSubfield = "-.[^-]*" 14 | 15 | // List of ADEXP tokens 16 | tokenTitle = "TITLE" 17 | tokenAdep = "ADEP" 18 | tokenAltnz = "ALTNZ" 19 | tokenAdes = "ADES" 20 | tokenArcid = "ARCID" 21 | tokenArctyp = "ARCTYP" 22 | tokenCeqpt = "CEQPT" 23 | tokenMsgtxt = "MSGTXT" 24 | tokenComment = "COMMENT" 25 | tokenEetfir = "EETFIR" 26 | tokenSpeed = "SPEED" 27 | tokenEstdata = "ESTDATA" 28 | tokenGeo = "GEO" 29 | tokenRtepts = "RTEPTS" 30 | 31 | // List of ADEXP subtokens 32 | subtokenPtid = "PTID" 33 | subtokenEto = "ETO" 34 | subtokenFl = "FL" 35 | subtokenGeoid = "GEOID" 36 | subtokenLattd = "LATTD" 37 | subtokenLongtd = "LONGTD" 38 | ) 39 | 40 | var ( 41 | bytesNewline = []byte("\n") 42 | bytesNewlineDash = []byte("\n-") 43 | bytesBegin = []byte("-BEGIN") 44 | bytesEnd = []byte("-END") 45 | bytesEmpty = []byte(" ") 46 | bytesComment = []byte("//") 47 | bytesDash = []byte("-") 48 | 49 | regexpSubfield, _ = regexp.Compile(patternSubfield) 50 | 51 | // Map containing the mapping function given a specific token name 52 | factory = map[string]func(string, []byte) interface{}{ 53 | tokenTitle: parseSimpleToken, 54 | tokenAdep: parseSimpleToken, 55 | tokenAltnz: parseSimpleToken, 56 | tokenAdes: parseSimpleToken, 57 | tokenArcid: parseSimpleToken, 58 | tokenArctyp: parseSimpleToken, 59 | tokenCeqpt: parseSimpleToken, 60 | tokenMsgtxt: parseSimpleToken, 61 | tokenComment: parseSimpleToken, 62 | 63 | tokenEetfir: parseSimpleToken, 64 | tokenSpeed: parseSimpleToken, 65 | 66 | tokenEstdata: parseComplexToken, 67 | tokenGeo: parseComplexToken, 68 | tokenRtepts: parseComplexToken, 69 | } 70 | ) 71 | 72 | // Parse an ADEXP message using a byte list as an input. This function returns a Message and an eventual error in case of a parsing error. 73 | func ParseAdexpMessage(bytes []byte) (Message, error) { 74 | log.Debugf("parsing: %v", string(bytes)) 75 | 76 | // Preprocessing 77 | preprocessed, err := preprocess(bytes) 78 | if err != nil { 79 | return Message{}, err 80 | } 81 | 82 | // Actual processing 83 | message, err := process(preprocessed) 84 | if err != nil { 85 | return Message{}, err 86 | } 87 | 88 | log.Debugf("returning message: %v", message) 89 | 90 | return message, nil 91 | } 92 | 93 | // Preprocessing of an ADEXP message (cleaning white spaces, rearranging multi-lined tokens etc.). Returns a byte list cleansed and an eventual error if the input is invalid. 94 | func preprocess(in []byte) ([][]byte, error) { 95 | if len(in) == 0 { 96 | log.Errorf("input is empty") 97 | return nil, errors.New("input is empty") 98 | } 99 | 100 | lines := bytes.Split(in, bytesNewline) 101 | var result [][]byte 102 | var currentLine []byte 103 | 104 | for _, line := range lines { 105 | if startWith(line, bytesEnd) { 106 | // Nothing 107 | } else if startWith(line, bytesBegin) { 108 | result = append(result, currentLine) 109 | 110 | trimed := bytes.Trim(line, " ") 111 | currentLine = append(bytesDash, trimed[len(bytesBegin)+1:]...) 112 | } else if startWith(line, bytesDash) { 113 | result = append(result, currentLine) 114 | 115 | currentLine = bytes.Trim(line, " ") 116 | } else if startWith(line, bytesEmpty) { 117 | currentLine = append(append(currentLine, bytesEmpty...), bytes.Trim(line, " ")...) 118 | } else { 119 | currentLine = append(append(currentLine, bytesEmpty...), bytes.Trim(line, " ")...) 120 | } 121 | } 122 | 123 | if len(currentLine) > 0 { 124 | result = append(result, currentLine) 125 | } 126 | 127 | return result, nil 128 | } 129 | 130 | // Processing of an ADEXP message. Returns a Message structure and an eventual error in case of a processing error. 131 | func process(in [][]byte) (Message, error) { 132 | nLines := len(in) 133 | 134 | // Create a channel for goroutine responses 135 | ch := make(chan interface{}, nLines) 136 | 137 | // Split each line in a goroutine 138 | for _, line := range in { 139 | go mapLine(line, ch) 140 | } 141 | 142 | msg := Message{} 143 | 144 | // Gather the goroutine results 145 | for range in { 146 | data := <-ch 147 | 148 | // A mapper function can return a nil value (a line is potentially invalid, a comment etc.). In that case we simply discard the line. 149 | if data == nil { 150 | continue 151 | } 152 | 153 | // Enrich the message depending on the data type sent by the goroutines 154 | switch data.(type) { 155 | case simpleToken: 156 | simpleToken := data.(simpleToken) 157 | value := simpleToken.value 158 | switch simpleToken.token { 159 | case tokenTitle: 160 | msg.Title = value 161 | case tokenAdep: 162 | msg.Adep = value 163 | case tokenAltnz: 164 | msg.Alternate = value 165 | case tokenAdes: 166 | msg.Ades = value 167 | case tokenArcid: 168 | msg.Arcid = value 169 | case tokenArctyp: 170 | msg.ArcType = value 171 | case tokenCeqpt: 172 | msg.Ceqpt = value 173 | case tokenMsgtxt: 174 | msg.MessageText = value 175 | case tokenComment: 176 | msg.Comment = value 177 | case tokenEetfir: 178 | msg.Eetfir = append(msg.Eetfir, value) 179 | case tokenSpeed: 180 | msg.Speed = append(msg.Speed, value) 181 | default: 182 | log.Errorf("unexpected token type %v", simpleToken.token) 183 | return Message{}, fmt.Errorf("unexpected token type %v", simpleToken.token) 184 | } 185 | case complexToken: 186 | complexToken := data.(complexToken) 187 | value := complexToken.value 188 | 189 | switch complexToken.token { 190 | case tokenEstdata: 191 | for _, v := range value { 192 | fl, err := extractFlightLevel(v[subtokenFl]) 193 | if err != nil { 194 | return Message{}, fmt.Errorf("flight level %v cannot be parsed", fl) 195 | } 196 | msg.Estdata = append(msg.Estdata, estdata{v[subtokenPtid], v[subtokenEto], fl}) 197 | } 198 | case tokenGeo: 199 | for _, v := range value { 200 | msg.Geo = append(msg.Geo, geo{v[subtokenGeoid], v[subtokenLattd], v[subtokenLongtd]}) 201 | } 202 | case tokenRtepts: 203 | for _, v := range value { 204 | fl, err := extractFlightLevel(v[subtokenFl]) 205 | if err != nil { 206 | return Message{}, fmt.Errorf("flight level %v cannot be parsed", fl) 207 | } 208 | msg.RoutePoints = append(msg.RoutePoints, rtepts{v[subtokenPtid], fl, v[subtokenEto]}) 209 | } 210 | default: 211 | log.Errorf("unexpected token type %v", complexToken.token) 212 | return Message{}, fmt.Errorf("unexpected token type %v", complexToken.token) 213 | } 214 | } 215 | } 216 | 217 | msg.Type = AdexpType 218 | 219 | return msg, nil 220 | } 221 | 222 | // Process a line and returns a token to the channel 223 | func mapLine(in []byte, ch chan interface{}) { 224 | // Filter empty lines and comment lines 225 | if len(in) == 0 || startWith(in, bytesComment) { 226 | ch <- nil 227 | return 228 | } 229 | 230 | token, value := parseLine(in) 231 | if token == nil { 232 | ch <- nil 233 | log.Warnf("Token name is empty on line %v", string(in)) 234 | return 235 | } 236 | 237 | sToken := string(token) 238 | 239 | // Checks in the factory map if the token has been configured 240 | if f, contains := factory[sToken]; contains { 241 | ch <- f(sToken, value) 242 | return 243 | } 244 | 245 | log.Warnf("Token %v is not managed by the parser", string(in)) 246 | ch <- nil 247 | } 248 | 249 | // Parse a simple token and returns a simpleToken structure 250 | func parseSimpleToken(token string, value []byte) interface{} { 251 | return simpleToken{token, string(value)} 252 | } 253 | 254 | // Parse a complex token and returns a commplexToken structure 255 | func parseComplexToken(token string, value []byte) interface{} { 256 | if value == nil { 257 | log.Warnf("Empty value") 258 | return complexToken{token, nil} 259 | } 260 | 261 | var v []map[string]string 262 | currentMap := make(map[string]string) 263 | 264 | // Find all subfields 265 | matches := regexpSubfield.FindAll(value, -1) 266 | 267 | // Iterate over each subfields to enrich the returned data 268 | for _, sub := range matches { 269 | h, l := parseLine(sub) 270 | 271 | if _, contains := currentMap[string(h)]; contains { 272 | v = append(v, currentMap) 273 | currentMap = make(map[string]string) 274 | } 275 | 276 | currentMap[string(h)] = string(bytes.Trim(l, " ")) 277 | } 278 | 279 | // Append the latest map 280 | v = append(v, currentMap) 281 | 282 | return complexToken{token, v} 283 | } 284 | -------------------------------------------------------------------------------- /good/adexp_test.go: -------------------------------------------------------------------------------- 1 | package good 2 | 3 | import ( 4 | log "github.com/sirupsen/logrus" 5 | "github.com/stretchr/testify/assert" 6 | "io/ioutil" 7 | "testing" 8 | ) 9 | 10 | // Test the parsing of a simple ADEXP message 11 | func TestParseAdexpMessage(t *testing.T) { 12 | bytes, _ := ioutil.ReadFile("../resources/tests/adexp.txt") 13 | 14 | m, _ := ParseAdexpMessage(bytes) 15 | 16 | // Test upper level 17 | assert.Equal(t, true, m.IsUpperLevel()) 18 | 19 | // Simple 20 | assert.Equal(t, "IFPL", m.Title) 21 | assert.Equal(t, "CYYZ", m.Adep) 22 | assert.Equal(t, "EASTERN :CREEK'()+,./", m.Alternate) 23 | assert.Equal(t, "AFIL", m.Ades) 24 | assert.Equal(t, "ACA878", m.Arcid) 25 | assert.Equal(t, "A333", m.ArcType) 26 | assert.Equal(t, "SDE3FGHIJ3J5LM1ORVWXY", m.Ceqpt) 27 | 28 | // Repeating 29 | assert.Equal(t, 13, len(m.Eetfir)) 30 | assert.Equal(t, 2, len(m.Speed)) 31 | 32 | // Complex 33 | assert.Equal(t, 2, len(m.Estdata)) 34 | assert.Equal(t, 3, len(m.Geo)) 35 | assert.Equal(t, 5, len(m.RoutePoints)) 36 | 37 | // Route points 38 | assert.Equal(t, "CYYZ", m.RoutePoints[0].Ptid) 39 | assert.Equal(t, 0, m.RoutePoints[0].FlightLevel) 40 | assert.Equal(t, "170301220429", m.RoutePoints[0].Eto) 41 | assert.Equal(t, "JOOPY", m.RoutePoints[1].Ptid) 42 | assert.Equal(t, 390, m.RoutePoints[1].FlightLevel) 43 | assert.Equal(t, "170302002327", m.RoutePoints[1].Eto) 44 | assert.Equal(t, "GEO01", m.RoutePoints[2].Ptid) 45 | assert.Equal(t, 390, m.RoutePoints[2].FlightLevel) 46 | assert.Equal(t, "170302003347", m.RoutePoints[2].Eto) 47 | assert.Equal(t, "BLM", m.RoutePoints[3].Ptid) 48 | assert.Equal(t, 171, m.RoutePoints[3].FlightLevel) 49 | assert.Equal(t, "170302051642", m.RoutePoints[3].Eto) 50 | assert.Equal(t, "LSZH", m.RoutePoints[4].Ptid) 51 | assert.Equal(t, 14, m.RoutePoints[4].FlightLevel) 52 | assert.Equal(t, "170302052710", m.RoutePoints[4].Eto) 53 | } 54 | 55 | // Test ... 56 | func TestParseSimpleToken(t *testing.T) { 57 | // Do something 58 | } 59 | 60 | // Test ... 61 | func TestParseComplexToken(t *testing.T) { 62 | // Do something 63 | } 64 | 65 | // Performance test of an ADEXP message parsing 66 | func BenchmarkParseAdexpMessage(t *testing.B) { 67 | log.SetLevel(log.FatalLevel) 68 | bytes, _ := ioutil.ReadFile("../resources/tests/adexp.txt") 69 | 70 | for i := 0; i < t.N; i++ { 71 | ParseAdexpMessage(bytes) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /good/aftn.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package good is a library for parsing the ADEXP messages. 3 | An intermediate format Message is built by the parser. 4 | */ 5 | 6 | package good 7 | 8 | import ( 9 | log "github.com/sirupsen/logrus" 10 | "os" 11 | ) 12 | 13 | func init() { 14 | // These parts should be configurable obviously but for the sake of this exercise we will let them hardcoded. 15 | log.SetOutput(os.Stdout) 16 | log.SetLevel(log.DebugLevel) 17 | } 18 | 19 | // AFTN message types 20 | const ( 21 | AdexpType = iota 22 | IcaoType = iota 23 | ) 24 | 25 | // Upper level constant 26 | const upperLevel = 350 27 | 28 | // Estimated data 29 | type estdata struct { 30 | Ptid string // Point id 31 | Eto string // Estimated Time Over 32 | FlightLevel int // Flight level 33 | } 34 | 35 | // Geo point 36 | type geo struct { 37 | Geoid string // Geo point id 38 | Latitude string // Point latitude 39 | Longitude string // Point longitude 40 | } 41 | 42 | // Route points 43 | type rtepts struct { 44 | Ptid string // Point id 45 | FlightLevel int // Flight level 46 | Eto string // Estimated Time Over 47 | } 48 | 49 | // Message structure produced by the parser 50 | type Message struct { 51 | Type int // Message type (ADEXP or ICAO) 52 | Title string // Message title 53 | Adep string // Departure airport 54 | Ades string // Destination airport 55 | Alternate string // Alternate aerodrome 56 | Arcid string // Aircraft identifier 57 | ArcType string // Aircraft type 58 | Ceqpt string // Equipment 59 | MessageText string // Message text 60 | Comment string // Personal comments 61 | Eetfir []string // Flight information region 62 | Speed []string // Speed 63 | Estdata []estdata // Estimated data 64 | Geo []geo // Geo points 65 | RoutePoints []rtepts // Route points 66 | } 67 | 68 | // Structure returned for parsing simple tokens 69 | type simpleToken struct { 70 | token string 71 | value string 72 | } 73 | 74 | // Structure returned for parsing complex tokens 75 | type complexToken struct { 76 | token string 77 | value []map[string]string 78 | } 79 | 80 | // Checks whether a message concerns the upper level (FL350) 81 | func (m *Message) IsUpperLevel() bool { 82 | for _, r := range m.RoutePoints { 83 | if r.FlightLevel > upperLevel { 84 | return true 85 | } 86 | } 87 | 88 | return false 89 | } 90 | -------------------------------------------------------------------------------- /good/icao.go: -------------------------------------------------------------------------------- 1 | package good 2 | 3 | // Parse an ICAO message and returns a Message structure and an eventual error 4 | func ParseIcaoMessage(bytes []byte) (Message, error) { 5 | // Do something 6 | 7 | return Message{Type: IcaoType}, nil 8 | } 9 | -------------------------------------------------------------------------------- /good/util.go: -------------------------------------------------------------------------------- 1 | package good 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | log "github.com/sirupsen/logrus" 7 | "strconv" 8 | ) 9 | 10 | // Check whether a byte slice starts with another byte slice 11 | func startWith(in, test []byte) bool { 12 | if len(test) > len(in) { 13 | return false 14 | } 15 | 16 | i := 0 17 | for range test { 18 | if test[i] != in[i] { 19 | return false 20 | } 21 | i++ 22 | } 23 | 24 | return true 25 | } 26 | 27 | // Parse a line by returning the header (token name) and the value. Example: -COMMENT TEST must returns COMMENT and TEST (in byte slices) 28 | func parseLine(in []byte) ([]byte, []byte) { 29 | if len(in) == 0 { 30 | return nil, nil 31 | } 32 | 33 | i := bytes.Index(in, bytesEmpty) 34 | 35 | if i == -1 { 36 | return in[1:], nil 37 | } 38 | 39 | return in[1:i], in[i+1:] 40 | } 41 | 42 | // As each flight level in represented as Fxxx (e.g. F350), this function simply parse the flight level to an int with an eventual error (if the int conversion fails for instance) 43 | func extractFlightLevel(in string) (int, error) { 44 | fl, err := strconv.Atoi(in[1:]) 45 | 46 | if err != nil { 47 | log.Errorf("flight level %v cannot be parsed", fl) 48 | return -1, fmt.Errorf("flight level %v cannot be parsed", fl) 49 | } 50 | 51 | return fl, err 52 | } 53 | -------------------------------------------------------------------------------- /resources/tests/adexp.txt: -------------------------------------------------------------------------------- 1 | -TITLE IFPL 2 | -ADEP CYYZ 3 | -ALTNZ EASTERN :CREEK'()+,./ 4 | -ADES AFIL 5 | -ARCID ACA878 6 | -ARCTYP A333 7 | -CEQPT SDE3FGHIJ3J5LM1ORVWXY 8 | -EETFIR KZLC 0035 9 | -EETFIR KZDV 0131 10 | -EETFIR KZMP 0200 11 | -EETFIR CZWG 0247 12 | -EETFIR CZUL 0349 13 | -EETFIR CZQX 0459 14 | -EETFIR EGGX 0655 15 | -EETFIR EGPX 0800 16 | -EETFIR EGTT 0831 17 | -EETFIR EHAA 0853 18 | -EETFIR EBBU 0908 19 | -EETFIR EDGG 0921 20 | -EETFIR EDUU 0921 21 | -ESTDATA -PTID XETBO -ETO 170302032300 -FL F390 22 | -ESTDATA -PTID ARKIL -ETO 170302032300 -FL F390 23 | -GEO -GEOID GEO01 -LATTD 490000N -LONGTD 0500000W 24 | -GEO -GEOID GEO02 -LATTD 500000N -LONGTD 0400000W 25 | -GEO -GEOID GEO04 -LATTD 520000N -LONGTD 0200000W 26 | -BEGIN RTEPTS 27 | -PT -PTID CYYZ -FL F000 -ETO 170301220429 28 | -PT -PTID JOOPY -FL F390 -ETO 170302002327 29 | -PT -PTID GEO01 -FL F390 -ETO 170302003347 30 | -PT -PTID BLM -FL F171 -ETO 170302051642 31 | -PT -PTID LSZH -FL F014 -ETO 170302052710 32 | -END RTEPTS 33 | -SPEED N0456 ARKIL 34 | -SPEED N0457 LIZAD 35 | -MSGTXT (ACH-BEL20B-LIML1050-EBBR-DOF/150521-14/HOC/1120F320 -18/PBN/B1 DOF/150521 REG/OODWK RVR/150 OPR/BEL ORGN/LSAZZQZG SRC/AFP RMK/AGCS EQUIPPED) 36 | -COMMENT ???FPD.F15: N0410F300 ARLES UL153 PUNSA/N0410F300 UL153 37 | VADEM/N0400F320 UN853 PENDU/N0400F330 UN853 IXILU/N0400F340 UN853 38 | DIK/N0400F320 UY37 BATTY --------------------------------------------------------------------------------