1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "android-base/parseint.h" 18 19 #include <gtest/gtest.h> 20 21 TEST(parseint, signed_smoke) { 22 int i = 0; 23 ASSERT_FALSE(android::base::ParseInt("x", &i)); 24 ASSERT_FALSE(android::base::ParseInt("123x", &i)); 25 26 ASSERT_TRUE(android::base::ParseInt("123", &i)); 27 ASSERT_EQ(123, i); 28 ASSERT_TRUE(android::base::ParseInt("-123", &i)); 29 ASSERT_EQ(-123, i); 30 31 short s = 0; 32 ASSERT_TRUE(android::base::ParseInt("1234", &s)); 33 ASSERT_EQ(1234, s); 34 35 ASSERT_TRUE(android::base::ParseInt("12", &i, 0, 15)); 36 ASSERT_EQ(12, i); 37 ASSERT_FALSE(android::base::ParseInt("-12", &i, 0, 15)); 38 ASSERT_FALSE(android::base::ParseInt("16", &i, 0, 15)); 39 } 40 41 TEST(parseint, unsigned_smoke) { 42 unsigned int i = 0u; 43 ASSERT_FALSE(android::base::ParseUint("x", &i)); 44 ASSERT_FALSE(android::base::ParseUint("123x", &i)); 45 46 ASSERT_TRUE(android::base::ParseUint("123", &i)); 47 ASSERT_EQ(123u, i); 48 ASSERT_FALSE(android::base::ParseUint("-123", &i)); 49 50 unsigned short s = 0u; 51 ASSERT_TRUE(android::base::ParseUint("1234", &s)); 52 ASSERT_EQ(1234u, s); 53 54 ASSERT_TRUE(android::base::ParseUint("12", &i, 15u)); 55 ASSERT_EQ(12u, i); 56 ASSERT_FALSE(android::base::ParseUint("-12", &i, 15u)); 57 ASSERT_FALSE(android::base::ParseUint("16", &i, 15u)); 58 } 59 60 TEST(parseint, no_implicit_octal) { 61 int i = 0; 62 ASSERT_TRUE(android::base::ParseInt("0123", &i)); 63 ASSERT_EQ(123, i); 64 65 unsigned int u = 0u; 66 ASSERT_TRUE(android::base::ParseUint("0123", &u)); 67 ASSERT_EQ(123u, u); 68 } 69 70 TEST(parseint, explicit_hex) { 71 int i = 0; 72 ASSERT_TRUE(android::base::ParseInt("0x123", &i)); 73 ASSERT_EQ(0x123, i); 74 75 unsigned int u = 0u; 76 ASSERT_TRUE(android::base::ParseUint("0x123", &u)); 77 ASSERT_EQ(0x123u, u); 78 } 79 80 TEST(parseint, string) { 81 int i = 0; 82 ASSERT_TRUE(android::base::ParseInt(std::string("123"), &i)); 83 ASSERT_EQ(123, i); 84 85 unsigned int u = 0u; 86 ASSERT_TRUE(android::base::ParseUint(std::string("123"), &u)); 87 ASSERT_EQ(123u, u); 88 } 89 90 TEST(parseint, untouched_on_failure) { 91 int i = 123; 92 ASSERT_FALSE(android::base::ParseInt("456x", &i)); 93 ASSERT_EQ(123, i); 94 95 unsigned int u = 123u; 96 ASSERT_FALSE(android::base::ParseInt("456x", &u)); 97 ASSERT_EQ(123u, u); 98 } 99