Skip to content

Instantly share code, notes, and snippets.

@akingdom
Last active September 28, 2023 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akingdom/4ca0ba8cd704b31a4a5a4b2c3d1d1a3f to your computer and use it in GitHub Desktop.
Save akingdom/4ca0ba8cd704b31a4a5a4b2c3d1d1a3f to your computer and use it in GitHub Desktop.
// Swift
//
// Intent: Process a simple memory-resident ASCII-style string in UTF8 format.
//
// Reads Data as a string, line by line,
// similar to how FileHandle works with a file pointer index.
// There are better ways to do this.
//
// By Andrew Kingdom
// MIT license
//
import Foundation
class ReadDataLines {
// The 'searchIndex' parameter should normally be initialised to 0 (the first character index)
// When there is no more data, a null result is returned.
static func readLine(from data: Data, searchIndex: inout Int) throws -> String? {
var startIndex = searchIndex
if(startIndex < 0 || startIndex >= data.count) { return nil }
// Find the next newline character in the data starting from the given index.
if(!findNextOccurrence(of: 0x0a, in: data, index: &searchIndex)) {
// If we reach the end of the data without finding a newline character, return the remaining data as the line.
let remainder = String(data: data[startIndex..<data.count], encoding: .utf8)
return remainder
} else {
// newline found -- return the line up to the newline character.
let line = String(data: data[startIndex..<searchIndex], encoding: .utf8)
// Update the index pointer to point to the character after the newline character.
searchIndex += 1
return line
}
}
// index should be initialised to 0.
// Result is false if there was no found match.
static func findNextOccurrence(of character: UInt8, in data: Data, index: inout Int) -> Bool {
for i in index..<data.count {
if data[i] == character {
index = i
return true
}
}
index = data.count
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment