OLD | NEW |
(Empty) | |
| 1 // Copyright 2017 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 "components/physical_web/eddystone/eddystone_encoder.h" |
| 6 |
| 7 #include <string> |
| 8 #include <vector> |
| 9 |
| 10 #include "url/gurl.h" |
| 11 |
| 12 namespace { |
| 13 const char* kPrefixes[] = {"http://www.", "https://www.", "http://", |
| 14 "https://"}; |
| 15 const size_t kNumPrefixes = sizeof(kPrefixes) / sizeof(char*); |
| 16 |
| 17 const char* kSuffixes[] = {".com/", ".org/", ".edu/", ".net/", ".info/", |
| 18 ".biz/", ".gov/", ".com", ".org", ".edu", |
| 19 ".net", ".info", ".biz", ".gov"}; |
| 20 const size_t kNumSuffixes = sizeof(kSuffixes) / sizeof(char*); |
| 21 } |
| 22 |
| 23 namespace physical_web { |
| 24 int EncodeUrl(const std::string& url, std::vector<uint8_t>* encoded_url) { |
| 25 /* |
| 26 * Sanitize input. |
| 27 */ |
| 28 |
| 29 if (encoded_url == NULL) |
| 30 return kNullEncodedUrl; |
| 31 if (url.empty()) |
| 32 return kEmptyUrl; |
| 33 |
| 34 GURL gurl(url); |
| 35 if (!gurl.is_valid()) |
| 36 return kInvalidUrl; |
| 37 if (gurl.HostIsIPAddress() || !gurl.SchemeIsHTTPOrHTTPS()) |
| 38 return kInvalidFormat; |
| 39 |
| 40 /* |
| 41 * Necessary Declarations. |
| 42 */ |
| 43 const char* raw_url_position = url.c_str(); |
| 44 |
| 45 static bool lengths_loaded = false; |
| 46 static size_t prefix_lengths[kNumPrefixes]; |
| 47 static size_t suffix_lengths[kNumSuffixes]; |
| 48 |
| 49 if (!lengths_loaded) { |
| 50 for (size_t i = 0; i < kNumPrefixes; i++) { |
| 51 prefix_lengths[i] = strlen(kPrefixes[i]); |
| 52 } |
| 53 for (size_t i = 0; i < kNumSuffixes; i++) { |
| 54 suffix_lengths[i] = strlen(kSuffixes[i]); |
| 55 } |
| 56 lengths_loaded = true; |
| 57 } |
| 58 |
| 59 /* |
| 60 * Handle prefix. |
| 61 */ |
| 62 for (size_t i = 0; i < kNumPrefixes; i++) { |
| 63 size_t prefix_len = prefix_lengths[i]; |
| 64 if (strncmp(raw_url_position, kPrefixes[i], prefix_len) == 0) { |
| 65 encoded_url->push_back(i); |
| 66 raw_url_position += prefix_len; |
| 67 break; |
| 68 } |
| 69 } |
| 70 |
| 71 /* |
| 72 * Handle suffixes. |
| 73 */ |
| 74 while (*raw_url_position) { |
| 75 /* check for suffix match */ |
| 76 size_t i; |
| 77 for (i = 0; i < kNumSuffixes; i++) { |
| 78 size_t suffix_len = suffix_lengths[i]; |
| 79 if (strncmp(raw_url_position, kSuffixes[i], suffix_len) == 0) { |
| 80 encoded_url->push_back(i); |
| 81 raw_url_position += suffix_len; |
| 82 break; /* from the for loop for checking against suffixes */ |
| 83 } |
| 84 } |
| 85 /* This is the default case where we've got an ordinary character which |
| 86 * doesn't match a suffix. */ |
| 87 if (i == kNumSuffixes) { |
| 88 encoded_url->push_back(*raw_url_position++); |
| 89 } |
| 90 } |
| 91 |
| 92 return encoded_url->size(); |
| 93 } |
| 94 } |
OLD | NEW |