Line data Source code
1 : // Copyright (c) 2011 The LevelDB 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. See the AUTHORS file for names of contributors.
4 :
5 : #include "util/logging.h"
6 :
7 : #include <errno.h>
8 : #include <stdarg.h>
9 : #include <stdio.h>
10 : #include <stdlib.h>
11 : #include "leveldb/env.h"
12 : #include "leveldb/slice.h"
13 :
14 : namespace leveldb {
15 :
16 0 : void AppendNumberTo(std::string* str, uint64_t num) {
17 : char buf[30];
18 : snprintf(buf, sizeof(buf), "%llu", (unsigned long long) num);
19 0 : str->append(buf);
20 0 : }
21 :
22 0 : void AppendEscapedStringTo(std::string* str, const Slice& value) {
23 0 : for (size_t i = 0; i < value.size(); i++) {
24 0 : char c = value[i];
25 0 : if (c >= ' ' && c <= '~') {
26 0 : str->push_back(c);
27 : } else {
28 : char buf[10];
29 : snprintf(buf, sizeof(buf), "\\x%02x",
30 0 : static_cast<unsigned int>(c) & 0xff);
31 0 : str->append(buf);
32 : }
33 : }
34 0 : }
35 :
36 0 : std::string NumberToString(uint64_t num) {
37 : std::string r;
38 0 : AppendNumberTo(&r, num);
39 0 : return r;
40 : }
41 :
42 0 : std::string EscapeString(const Slice& value) {
43 : std::string r;
44 0 : AppendEscapedStringTo(&r, value);
45 0 : return r;
46 : }
47 :
48 2230 : bool ConsumeDecimalNumber(Slice* in, uint64_t* val) {
49 2230 : uint64_t v = 0;
50 2230 : int digits = 0;
51 13112 : while (!in->empty()) {
52 10140 : char c = (*in)[0];
53 10140 : if (c >= '0' && c <= '9') {
54 8652 : ++digits;
55 8652 : const int delta = (c - '0');
56 : static const uint64_t kMaxUint64 = ~static_cast<uint64_t>(0);
57 17304 : if (v > kMaxUint64/10 ||
58 8652 : (v == kMaxUint64/10 && delta > kMaxUint64%10)) {
59 : // Overflow
60 : return false;
61 : }
62 8652 : v = (v * 10) + delta;
63 8652 : in->remove_prefix(1);
64 : } else {
65 : break;
66 : }
67 : }
68 2230 : *val = v;
69 2230 : return (digits > 0);
70 : }
71 :
72 : } // namespace leveldb
|