 
         let expectedEndPointer = buffer.pointer.advanced(by: length)
 
-        unknownFieldsStack.append(nil)
+        messageStackDepth += 1
         try decode(length)
-        let unknownFieldsData = unknownFieldsStack.popLast()!
+
+        let unknownFieldsData = unknownFieldsByMessageDepth?.removeValue(forKey: messageStackDepth)
+        messageStackDepth -= 1
 
         if buffer.pointer != expectedEndPointer {
             throw ProtoDecoder.Error.invalidStructure(


    private let buffer: ReadBuffer

    /** Buffers for unknown fields as a stack corresponding to message nesting.. */
    private var unknownFieldsStack: [WriteBuffer?] = []

    /** The encoding of the next value to be read. */
    private var nextFieldWireType: FieldWireType? = nil

    init(buffer: ReadBuffer) {
        self.buffer = buffer
        self.state = .lengthDelimited(length: buffer.count)
        self.messageStackDepth = 1
    }

    // MARK: - Public Methods - Iterating Tags
