title: Read exactly n bytes from InputStream in Swift 4
body: <p>I have a server that sends me messages over TCP where the first 4 bytes determine the length of the rest of the message. So I need to</p>
  
  <p>1) read 4 bytes into an UInt32 (works) and store it into <em>bytes_expected</em></p>
  
  <p>2) read <em>bytes_expected</em> bytes into <em>message</em></p>
  
  <p>Right now my code looks like this:</p>
  
  <pre><code>private let inputStreamAccessQueue  = DispatchQueue(label: "SynchronizedInputStreamAccess")
  </code></pre>
  
  <hr>
  
  <pre><code>func inputStreamHandler(_ event: Stream.Event) {
      switch event {
          case Stream.Event.hasBytesAvailable:
              self.handleInput()
  
          ...
      }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>func handleInput() {
      // **QUESTION: Do I use this barrier wrong?**
      self.inputStreamAccessQueue.sync(flags: .barrier) {            
          guard let istr = self.inputStream else {
              log.error(self.buildLogMessage("InputStream is nil"))
              return
          }
  
          guard istr.hasBytesAvailable else {
              log.error(self.buildLogMessage("handleInput() called when inputstream has no bytes available"))
              return
          }
  
          let lengthbuffer = UnsafeMutablePointer&lt;UInt8&gt;.allocate(capacity: 4)
          defer { lengthbuffer.deallocate(capacity: 4) }
          let lenbytes_read = istr.read(lengthbuffer, maxLength: 4)
  
          guard lenbytes_read == 4 else {
              self.errorHandler(NetworkingError.InputError("Input Stream received \(lenbytes_read) (!=4) bytes"))
              return
          }
  
          let bytes_expected = Int(UnsafeRawPointer(lengthbuffer).load(as: UInt32.self).bigEndian)
          log.info(self.buildLogMessage("expect \(bytes_expected) bytes"))
  
          print("::DEBUG", call, "bytes_expected", bytes_expected)
  
          var message = ""
          var bytes_missing = bytes_expected
          while bytes_missing &gt; 0 {
              //print("::DEBUG", call, "bytes_missing", bytes_missing)
              let buffer = UnsafeMutablePointer&lt;UInt8&gt;.allocate(capacity: bytes_missing)
              let bytes_read = istr.read(buffer, maxLength: bytes_missing)
  
              print("::DEBUG", call, "bytes_read", bytes_read)
  
              guard bytes_read &gt; 0 else {
                  print("bytes_read not &gt; 0: \(bytes_read)")
                  return
              }
  
              guard bytes_read &lt;= bytes_missing else {
                  print("Read more bytes than expected. missing=\(bytes_missing), read=\(bytes_read)")
                  return
              }
  
              guard let partial_message = String(bytesNoCopy: buffer, length: bytes_read, encoding: .utf8, freeWhenDone: true) else {
                  log.error("ERROR WHEN READING")
                  return
              }
  
              message = message + partial_message
              bytes_missing -= bytes_read
          }
  
          self.handleMessage(message)
      }
  }
  </code></pre>
  
  <p>My problem is that istr.read(buffer, maxLength: bytes_missing) sometimes does not read all messages at once, so I loop until I have read all I want. But I still see my app crashing (rarely) because handleInput() is called again while another call to that method is still running. In this case, bytes_expected contains random values and the app crashes due to illegal memory allocation.</p>
  
  <p>I thought I could avoid this by using the barrier. But it seems this does not work... Am I using the barrier wrong?</p>