blob: 6f6d321dfdabcd017c8a0e6e25389eb079f0d87d [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// Copyright 2018 by David A. Golden. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package stringprep
8
9var errHasLCat = "BiDi string can't have runes from category L"
10var errFirstRune = "BiDi string first rune must have category R or AL"
11var errLastRune = "BiDi string last rune must have category R or AL"
12
13// Check for prohibited characters from table C.8
14func checkBiDiProhibitedRune(s string) error {
15 for _, r := range s {
16 if TableC8.Contains(r) {
17 return Error{Msg: errProhibited, Rune: r}
18 }
19 }
20 return nil
21}
22
23// Check for LCat characters from table D.2
24func checkBiDiLCat(s string) error {
25 for _, r := range s {
26 if TableD2.Contains(r) {
27 return Error{Msg: errHasLCat, Rune: r}
28 }
29 }
30 return nil
31}
32
33// Check first and last characters are in table D.1; requires non-empty string
34func checkBadFirstAndLastRandALCat(s string) error {
35 rs := []rune(s)
36 if !TableD1.Contains(rs[0]) {
37 return Error{Msg: errFirstRune, Rune: rs[0]}
38 }
39 n := len(rs) - 1
40 if !TableD1.Contains(rs[n]) {
41 return Error{Msg: errLastRune, Rune: rs[n]}
42 }
43 return nil
44}
45
46// Look for RandALCat characters from table D.1
47func hasBiDiRandALCat(s string) bool {
48 for _, r := range s {
49 if TableD1.Contains(r) {
50 return true
51 }
52 }
53 return false
54}
55
56// Check that BiDi rules are satisfied ; let empty string pass this rule
57func passesBiDiRules(s string) error {
58 if len(s) == 0 {
59 return nil
60 }
61 if err := checkBiDiProhibitedRune(s); err != nil {
62 return err
63 }
64 if hasBiDiRandALCat(s) {
65 if err := checkBiDiLCat(s); err != nil {
66 return err
67 }
68 if err := checkBadFirstAndLastRandALCat(s); err != nil {
69 return err
70 }
71 }
72 return nil
73}