blob: 0d3869cf84c39574d37cf624824973d1880eb982 [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{
Jamie Madillc7be82a2015-06-01 14:14:04 -040058 unsigned int offset = 0;
59
60 if (input.size() >= 2 && input[0] == '0' && input[1] == 'x')
61 {
62 offset = 2u;
63 }
64
Jamie Madill8c5aeb62015-05-21 08:17:18 -040065 // Simple validity check
Jamie Madillc7be82a2015-06-01 14:14:04 -040066 if (input.find_first_not_of("0123456789ABCDEFabcdef", offset) != std::string::npos)
Jamie Madill8c5aeb62015-05-21 08:17:18 -040067 {
68 return false;
69 }
70
71 std::stringstream inStream(input);
72 inStream >> std::hex >> *uintOut;
73 return !inStream.fail();
74}
75
76bool ReadFileToString(const std::string &path, std::string *stringOut)
77{
78 std::ifstream inFile(path.c_str());
Jamie Madillc7be82a2015-06-01 14:14:04 -040079 if (inFile.fail())
80 {
81 return false;
82 }
Jamie Madill8c5aeb62015-05-21 08:17:18 -040083
84 inFile.seekg(0, std::ios::end);
Jamie Madillc7be82a2015-06-01 14:14:04 -040085 stringOut->reserve(static_cast<std::string::size_type>(inFile.tellg()));
Jamie Madill8c5aeb62015-05-21 08:17:18 -040086 inFile.seekg(0, std::ios::beg);
87
Jamie Madillc7be82a2015-06-01 14:14:04 -040088 stringOut->assign(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>());
Jamie Madill8c5aeb62015-05-21 08:17:18 -040089 return !inFile.fail();
90}
91
92}