pEpObjCAdapter/PEPCSVScanner.m
author Dirk Zimmermann <dz@pep.security>
Thu, 21 Mar 2019 12:37:32 +0100
branchrefactor
changeset 903 e9428f52fd88
parent 228 ef03cff2e1c4
permissions -rw-r--r--
IOS-1480 Merge IOS-1480 into refactor.
     1 //
     2 //  PEPCSVScanner.m
     3 //  pEpiOSAdapter
     4 //
     5 //  Created by Dirk Zimmermann on 03.05.17.
     6 //  Copyright © 2017 p≡p. All rights reserved.
     7 //
     8 
     9 #import "PEPCSVScanner.h"
    10 
    11 static unichar s_quoteChar = '"';
    12 
    13 @interface PEPCSVScanner ()
    14 
    15 @property (nonatomic) NSInteger position;
    16 @property (nonatomic) NSInteger len;
    17 
    18 @end;
    19 
    20 @implementation PEPCSVScanner
    21 
    22 - (instancetype _Nonnull )initWithString:(NSString * _Nonnull)string
    23 {
    24     if (self = [super init]) {
    25         _string = string;
    26         _len = [string length];
    27     }
    28     return self;
    29 }
    30 
    31 - (NSString * _Nullable)nextString
    32 {
    33     NSInteger startPos = NSNotFound;
    34     for (NSInteger thePos = self.position; thePos < self.len; thePos++) {
    35         if ([self startingQuoteAt:thePos]) {
    36             startPos = thePos + 1;
    37             for (NSInteger endPos = startPos; endPos < self.len; endPos++) {
    38                 if ([self endingQuoteAt:endPos]) {
    39                     self.position = endPos + 1;
    40                     return [self.string substringWithRange:NSMakeRange(startPos, endPos - startPos)];
    41                 }
    42             }
    43         }
    44     }
    45     return nil;
    46 }
    47 
    48 /**
    49  @return YES if the given position points to a starting quote.
    50  */
    51 - (BOOL)startingQuoteAt:(NSInteger)pos
    52 {
    53     // The last char can never be a starting quote
    54     if (pos >= self.len - 1) {
    55         return NO;
    56     }
    57     unichar ch1 = [self.string characterAtIndex:pos];
    58     unichar ch2 = [self.string characterAtIndex:pos + 1];
    59     if (ch1 == s_quoteChar && ch2 != s_quoteChar) {
    60         return YES;
    61     }
    62     return NO;
    63 }
    64 
    65 /**
    66  @return YES if the given position points to an ending quote.
    67  */
    68 - (BOOL)endingQuoteAt:(NSInteger)pos
    69 {
    70     unichar ch1 = [self.string characterAtIndex:pos];
    71     if (ch1 == s_quoteChar) {
    72         if (pos == self.len - 1) {
    73             return YES;
    74         }
    75         unichar ch2 = [self.string characterAtIndex:pos + 1];
    76         return ch2 != s_quoteChar;
    77     }
    78     return NO;
    79 }
    80 
    81 @end