summaryrefslogtreecommitdiff
path: root/media/cast/test/utility/input_helper.cc
blob: fa93926aa20b950b04d72fb8c1565f629382e6e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/cast/test/utility/input_helper.h"

#include <stdlib.h>
#include <cstdio>

#include "base/logging.h"
#include "base/strings/string_number_conversions.h"

namespace media {
namespace cast {
namespace test {

InputBuilder::InputBuilder(const std::string& title,
                           const std::string& default_value,
                           int low_range,
                           int high_range)
    : title_(title),
      default_value_(default_value),
      low_range_(low_range),
      high_range_(high_range) {}

InputBuilder::~InputBuilder() {}

std::string InputBuilder::GetStringInput() const {
  printf("\n%s\n", title_.c_str());
  if (!default_value_.empty())
    printf("Hit enter for default (%s):\n", default_value_.c_str());

  printf("# ");
  fflush(stdout);
  char raw_input[128];
  if (!fgets(raw_input, 128, stdin)) {
    NOTREACHED();
    return std::string();
  }

  std::string input = raw_input;
  input = input.substr(0, input.size() - 1);  // Strip last \n.
  if (input.empty() && !default_value_.empty())
    return default_value_;

  if (!ValidateInput(input)) {
    printf("Invalid input. Please try again.\n");
    return GetStringInput();
  }
  return input;
}

int InputBuilder::GetIntInput() const {
  std::string string_input = GetStringInput();
  int int_value;
  CHECK(base::StringToInt(string_input, &int_value));
  return int_value;
}

bool InputBuilder::ValidateInput(const std::string input) const {
  // Check for a valid range.
  if (low_range_ == INT_MIN && high_range_ == INT_MAX) return true;
  int value;
  if (!base::StringToInt(input, &value))
    return false;
  return value >= low_range_ && value <= high_range_;
}

}  // namespace test
}  // namespace cast
}  // namespace media