summaryrefslogtreecommitdiffstats
path: root/chrome/browser/sync/util/character_set_converters.cc
blob: 551ca2ba89e1624911c3217f42cee29a6f993063 (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
// Copyright (c) 2009 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 "chrome/browser/sync/util/character_set_converters.h"

namespace browser_sync {

void TrimPathStringToValidCharacter(std::string* string) {
  // Constants from http://en.wikipedia.org/wiki/UTF-8
  CHECK(string);
  if (string->empty())
    return;
  if (0 == (string->at(string->length() - 1) & 0x080))
    return;
  size_t partial_enc_bytes = 0;
  for (partial_enc_bytes = 0 ; true ; ++partial_enc_bytes) {
    if (4 == partial_enc_bytes || partial_enc_bytes == string->length()) {
      // original string was broken, garbage in, garbage out.
      return;
    }
    PathChar c = string->at(string->length() - 1 - partial_enc_bytes);
    if ((c & 0x0c0) == 0x080)  // utf continuation char;
      continue;
    if ((c & 0x0e0) == 0x0e0) {  // 2-byte encoded char.
      if (1 == partial_enc_bytes)
        return;
      else
        break;
    }
    if ((c & 0x0f0) == 0xc0) {  // 3-byte encoded char.
      if (2 == partial_enc_bytes)
        return;
      else
        break;
    }
    if ((c & 0x0f8) == 0x0f0) {  // 4-byte encoded char.
      if (3 == partial_enc_bytes)
        return;
      else
        break;
    }
  }
  string->resize(string->length() - 1 - partial_enc_bytes);
}

}  // namespace browser_sync