| 338 | } |
| 339 | |
| 340 | bool IsValid(const std::string &code) { |
| 341 | if (code.empty()) { |
| 342 | return false; |
| 343 | } |
| 344 | size_t separatorPos = code.find(internal::kSeparator); |
| 345 | // The separator is required. |
| 346 | if (separatorPos == std::string::npos) { |
| 347 | return false; |
| 348 | } |
| 349 | // There must only be one separator. |
| 350 | if (code.find_first_of(internal::kSeparator) != |
| 351 | code.find_last_of(internal::kSeparator)) { |
| 352 | return false; |
| 353 | } |
| 354 | // Is the separator the only character? |
| 355 | if (code.length() == 1) { |
| 356 | return false; |
| 357 | } |
| 358 | // Is the separator in an illegal position? |
| 359 | if (separatorPos > internal::kSeparatorPosition || separatorPos % 2 == 1) { |
| 360 | return false; |
| 361 | } |
| 362 | // We can have an even number of padding characters before the separator, |
| 363 | // but then it must be the final character. |
| 364 | std::size_t paddingStart = code.find_first_of(internal::kPaddingCharacter); |
| 365 | if (paddingStart != std::string::npos) { |
| 366 | // Short codes cannot have padding |
| 367 | if (separatorPos < internal::kSeparatorPosition) { |
| 368 | return false; |
| 369 | } |
| 370 | // The first padding character needs to be in an odd position. |
| 371 | if (paddingStart == 0 || paddingStart % 2) { |
| 372 | return false; |
| 373 | } |
| 374 | // Padded codes must not have anything after the separator |
| 375 | if (code.size() > separatorPos + 1) { |
| 376 | return false; |
| 377 | } |
| 378 | // Get from the first padding character to the separator |
| 379 | std::string paddingSection = |
| 380 | code.substr(paddingStart, internal::kSeparatorPosition - paddingStart); |
| 381 | paddingSection.erase( |
| 382 | std::remove(paddingSection.begin(), paddingSection.end(), |
| 383 | internal::kPaddingCharacter), |
| 384 | paddingSection.end()); |
| 385 | // After removing padding characters, we mustn't have anything left. |
| 386 | if (!paddingSection.empty()) { |
| 387 | return false; |
| 388 | } |
| 389 | } |
| 390 | // If there are characters after the separator, make sure there isn't just |
| 391 | // one of them (not legal). |
| 392 | if (code.size() - code.find(internal::kSeparator) - 1 == 1) { |
| 393 | return false; |
| 394 | } |
| 395 | // Are there any invalid characters? |
| 396 | for (char c : code) { |
| 397 | if (c != internal::kSeparator && c != internal::kPaddingCharacter && |