1/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 2 3Licensed under the Apache License, Version 2.0 (the "License"); 4you may not use this file except in compliance with the License. 5You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9Unless required by applicable law or agreed to in writing, software 10distributed under the License is distributed on an "AS IS" BASIS, 11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12See the License for the specific language governing permissions and 13limitations under the License. 14==============================================================================*/ 15#ifndef TENSORFLOW_CONTRIB_LITE_TESTING_SPLIT_H_ 16#define TENSORFLOW_CONTRIB_LITE_TESTING_SPLIT_H_ 17 18#include <cstdlib> 19#include <string> 20#include <utility> 21#include <vector> 22#include "tensorflow/contrib/lite/string.h" 23 24namespace tflite { 25namespace testing { 26 27// Splits a string based on the given delimiter string. Each pair in the 28// returned vector has the start and past-the-end positions for each of the 29// parts of the original string. Empty fields are not represented in the 30// output. 31std::vector<std::pair<size_t, size_t>> SplitToPos(const string& s, 32 const string& delimiter); 33 34// Splits the given string and converts each part to the given T. 35template <typename T> 36std::vector<T> Split(const string& s, const string& delimiter); 37 38template <> 39inline std::vector<string> Split(const string& s, const string& delimiter) { 40 std::vector<string> fields; 41 for (const auto& p : SplitToPos(s, delimiter)) { 42 fields.push_back(s.substr(p.first, p.second - p.first)); 43 } 44 return fields; 45} 46 47template <> 48inline std::vector<int> Split(const string& s, const string& delimiter) { 49 std::vector<int> fields; 50 for (const auto& p : SplitToPos(s, delimiter)) { 51 fields.push_back(strtol(s.data() + p.first, nullptr, 10)); 52 } 53 return fields; 54} 55 56template <> 57inline std::vector<int64_t> Split(const string& s, const string& delimiter) { 58 std::vector<int64_t> fields; 59 for (const auto& p : SplitToPos(s, delimiter)) { 60 fields.push_back(strtoll(s.data() + p.first, nullptr, 10)); 61 } 62 return fields; 63} 64 65template <> 66inline std::vector<float> Split(const string& s, const string& delimiter) { 67 std::vector<float> fields; 68 for (const auto& p : SplitToPos(s, delimiter)) { 69 fields.push_back(strtod(s.data() + p.first, nullptr)); 70 } 71 return fields; 72} 73 74template <> 75inline std::vector<uint8_t> Split(const string& s, const string& delimiter) { 76 std::vector<uint8_t> fields; 77 for (const auto& p : SplitToPos(s, delimiter)) { 78 fields.push_back(strtol(s.data() + p.first, nullptr, 10)); 79 } 80 return fields; 81} 82 83} // namespace testing 84} // namespace tflite 85 86#endif // TENSORFLOW_CONTRIB_LITE_TESTING_SPLIT_H_ 87