1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "media/cast/test/utility/input_helper.h"
6
7 #include <stdlib.h>
8 #include <cstdio>
9
10 #include "base/logging.h"
11 #include "base/strings/string_number_conversions.h"
12
13 namespace media {
14 namespace cast {
15 namespace test {
16
InputBuilder(const std::string & title,const std::string & default_value,int low_range,int high_range)17 InputBuilder::InputBuilder(const std::string& title,
18 const std::string& default_value,
19 int low_range,
20 int high_range)
21 : title_(title),
22 default_value_(default_value),
23 low_range_(low_range),
24 high_range_(high_range) {}
25
~InputBuilder()26 InputBuilder::~InputBuilder() {}
27
GetStringInput() const28 std::string InputBuilder::GetStringInput() const {
29 printf("\n%s\n", title_.c_str());
30 if (!default_value_.empty())
31 printf("Hit enter for default (%s):\n", default_value_.c_str());
32
33 printf("# ");
34 fflush(stdout);
35 char raw_input[128];
36 if (!fgets(raw_input, 128, stdin)) {
37 NOTREACHED();
38 return std::string();
39 }
40
41 std::string input = raw_input;
42 input = input.substr(0, input.size() - 1); // Strip last \n.
43 if (input.empty() && !default_value_.empty())
44 return default_value_;
45
46 if (!ValidateInput(input)) {
47 printf("Invalid input. Please try again.\n");
48 return GetStringInput();
49 }
50 return input;
51 }
52
GetIntInput() const53 int InputBuilder::GetIntInput() const {
54 std::string string_input = GetStringInput();
55 int int_value;
56 CHECK(base::StringToInt(string_input, &int_value));
57 return int_value;
58 }
59
ValidateInput(const std::string input) const60 bool InputBuilder::ValidateInput(const std::string input) const {
61 // Check for a valid range.
62 if (low_range_ == INT_MIN && high_range_ == INT_MAX) return true;
63 int value;
64 if (!base::StringToInt(input, &value))
65 return false;
66 return value >= low_range_ && value <= high_range_;
67 }
68
69 } // namespace test
70 } // namespace cast
71 } // namespace media
72