xref: /haiku/src/apps/terminal/PatternEvaluator.cpp (revision 4466b89c65970de4c7236ac87faa2bee4589f413)
1 /*
2  * Copyright 2010, Ingo Weinhold, ingo_weinhold@gmx.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include "PatternEvaluator.h"
8 
9 #include <ctype.h>
10 #include <stdlib.h>
11 #include <string.h>
12 
13 
14 
15 // #pragma mark - PatternEvaluator
16 
17 
18 /*static*/ BString
19 PatternEvaluator::Evaluate(const char* pattern, PlaceholderMapper& mapper)
20 {
21 	BString result;
22 
23 	while (*pattern != '\0') {
24 		// find next placeholder
25 		const char* placeholder = strchr(pattern, '%');
26 		if (placeholder == NULL)
27 			return result.Append(pattern);
28 
29 		// append skipped chars
30 		if (placeholder != pattern)
31 			result.Append(pattern, placeholder - pattern);
32 
33 		pattern = placeholder + 1;
34 
35 		// check for an escaped '%'
36 		if (*pattern == '%') {
37 			result += '%';
38 			pattern++;
39 			continue;
40 		}
41 
42 		// parse a number, if there is one
43 		int64 number = 0;
44 		bool hasNumber = false;
45 		if (isdigit(*pattern)) {
46 			char* numberEnd;
47 			number = strtoll(pattern, &numberEnd, 10);
48 			pattern = numberEnd;
49 			hasNumber = true;
50 		}
51 
52 		BString mappedValue;
53 		if (*pattern != '\0' && mapper.MapPlaceholder(*pattern,
54 				number, hasNumber, mappedValue)) {
55 			// mapped successfully -- append the replacement string
56 			result += mappedValue;
57 			pattern++;
58 		} else {
59 			// something went wrong -- just append the literal part of the
60 			// pattern
61 			result.Append(placeholder, pattern - placeholder);
62 		}
63 	}
64 
65 	return result;
66 }
67 
68 
69 
70 // #pragma mark - PlaceholderMapper
71 
72 
73 PatternEvaluator::PlaceholderMapper::~PlaceholderMapper()
74 {
75 }
76