Don Newton | 379ae25 | 2019-04-01 12:17:06 -0400 | [diff] [blame^] | 1 | // Copyright (C) MongoDB, Inc. 2017-present. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | // not use this file except in compliance with the License. You may obtain |
| 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | |
| 7 | package bsoncodec |
| 8 | |
| 9 | import "fmt" |
| 10 | |
| 11 | type mode int |
| 12 | |
| 13 | const ( |
| 14 | _ mode = iota |
| 15 | mTopLevel |
| 16 | mDocument |
| 17 | mArray |
| 18 | mValue |
| 19 | mElement |
| 20 | mCodeWithScope |
| 21 | mSpacer |
| 22 | ) |
| 23 | |
| 24 | func (m mode) String() string { |
| 25 | var str string |
| 26 | |
| 27 | switch m { |
| 28 | case mTopLevel: |
| 29 | str = "TopLevel" |
| 30 | case mDocument: |
| 31 | str = "DocumentMode" |
| 32 | case mArray: |
| 33 | str = "ArrayMode" |
| 34 | case mValue: |
| 35 | str = "ValueMode" |
| 36 | case mElement: |
| 37 | str = "ElementMode" |
| 38 | case mCodeWithScope: |
| 39 | str = "CodeWithScopeMode" |
| 40 | case mSpacer: |
| 41 | str = "CodeWithScopeSpacerFrame" |
| 42 | default: |
| 43 | str = "UnknownMode" |
| 44 | } |
| 45 | |
| 46 | return str |
| 47 | } |
| 48 | |
| 49 | // TransitionError is an error returned when an invalid progressing a |
| 50 | // ValueReader or ValueWriter state machine occurs. |
| 51 | type TransitionError struct { |
| 52 | parent mode |
| 53 | current mode |
| 54 | destination mode |
| 55 | } |
| 56 | |
| 57 | func (te TransitionError) Error() string { |
| 58 | if te.destination == mode(0) { |
| 59 | return fmt.Sprintf("invalid state transition: cannot read/write value while in %s", te.current) |
| 60 | } |
| 61 | if te.parent == mode(0) { |
| 62 | return fmt.Sprintf("invalid state transition: %s -> %s", te.current, te.destination) |
| 63 | } |
| 64 | return fmt.Sprintf("invalid state transition: %s -> %s; parent %s", te.current, te.destination, te.parent) |
| 65 | } |