blob: 171c50193250c63ba873d9eaea8f82eb09abb578 [file] [log] [blame]
Jamie Madill8c5aeb62015-05-21 08:17:18 -04001//
2// Copyright 2015 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// string_utils:
7// String helper functions.
8//
9
10#include "string_utils.h"
11
12#include <fstream>
13#include <sstream>
14
15namespace angle
16{
17
18void SplitString(const std::string &input,
19 char delimiter,
20 std::vector<std::string> *tokensOut)
21{
22 std::istringstream stream(input);
23 std::string token;
24
25 while (std::getline(stream, token, delimiter))
26 {
27 if (!token.empty())
28 {
29 tokensOut->push_back(token);
30 }
31 }
32}
33
34void SplitStringAlongWhitespace(const std::string &input,
35 std::vector<std::string> *tokensOut)
36{
37 const char *delimiters = " \f\n\r\t\v";
38
39 std::istringstream stream(input);
40 std::string line;
41
42 while (std::getline(stream, line))
43 {
44 size_t prev = 0, pos;
45 while ((pos = line.find_first_of(delimiters, prev)) != std::string::npos)
46 {
47 if (pos > prev)
48 tokensOut->push_back(line.substr(prev, pos - prev));
49 prev = pos + 1;
50 }
51 if (prev < line.length())
52 tokensOut->push_back(line.substr(prev, std::string::npos));
53 }
54}
55
56bool HexStringToUInt(const std::string &input, unsigned int *uintOut)
57{
58 // Simple validity check
59 if (input[0] != '0' || input[1] != 'x' ||
60 input.find_first_not_of("0123456789ABCDEFabcdef", 2) != std::string::npos)
61 {
62 return false;
63 }
64
65 std::stringstream inStream(input);
66 inStream >> std::hex >> *uintOut;
67 return !inStream.fail();
68}
69
70bool ReadFileToString(const std::string &path, std::string *stringOut)
71{
72 std::ifstream inFile(path.c_str());
73 std::string str;
74
75 inFile.seekg(0, std::ios::end);
76 str.reserve(inFile.tellg());
77 inFile.seekg(0, std::ios::beg);
78
79 str.assign(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>());
80 return !inFile.fail();
81}
82
83}