From a17a8c13c305ac5b45f35fa84f417684112c7532 Mon Sep 17 00:00:00 2001 From: tom Date: Fri, 8 Aug 2025 12:03:54 +0200 Subject: [PATCH] fix: output split n --- .../EngineMessenger/EngineMessenger.h | 1 + .../EngineMessenger/EngineMessenger.mm | 34 ++++++++++++++----- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.h b/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.h index dadaeb9..858441e 100644 --- a/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.h +++ b/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.h @@ -25,6 +25,7 @@ NS_SWIFT_SENDABLE /// Engines work asynchronously so use this block to subscribe to /// any commands received from the engine. @property (nullable) void (^ responseHandler)(NSString * _Nonnull response); +@property (nonatomic, strong) NSMutableString *outputBuffer; /// Initializes an engine with the desired type. /// diff --git a/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm b/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm index 38b39dd..74a7b41 100644 --- a/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm +++ b/Sources/ChessKitEngineCore/EngineMessenger/EngineMessenger.mm @@ -26,6 +26,7 @@ - (id)initWithEngineType: (EngineType_objc) type { if (self) { _lock = [[NSLock alloc] init]; + _outputBuffer = [NSMutableString string]; switch (type) { case EngineTypeStockfish: _engine = new StockfishEngine(); @@ -105,15 +106,30 @@ - (void)sendCommand: (NSString*) command { # pragma mark Private -- (void)readStdout: (NSNotification*) notification { - [_pipeReadHandle readInBackgroundAndNotify]; - - NSData *data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem]; - NSArray *output = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] componentsSeparatedByString:@"\n"]; - - [output enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { - [self responseHandler](obj); - }]; +- (void)readStdout:(NSNotification*)notification { + [_pipeReadHandle readInBackgroundAndNotify]; + + NSData *data = notification.userInfo[NSFileHandleNotificationDataItem]; + if (!data || data.length == 0) return; + + NSString *chunk = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + if (!chunk) return; + + [self.outputBuffer appendString:chunk]; + + NSArray *lines = [self.outputBuffer componentsSeparatedByString:@"\n"]; + + // Keep the last line in the buffer if it's incomplete + NSUInteger lastIndex = lines.count - 1; + for (NSUInteger i = 0; i < lastIndex; i++) { + NSString *line = lines[i]; + if (line.length > 0) { + [self responseHandler](line); + } + } + + // Reset the buffer with the last (possibly partial) line + [self.outputBuffer setString:lines[lastIndex]]; } @end