1// Copyright 2013 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package cldr 6 7import ( 8 "encoding/xml" 9 "regexp" 10 "strconv" 11) 12 13// Elem is implemented by every XML element. 14type Elem interface { 15 setEnclosing(Elem) 16 setName(string) 17 enclosing() Elem 18 19 GetCommon() *Common 20} 21 22type hidden struct { 23 CharData string `xml:",chardata"` 24 Alias *struct { 25 Common 26 Source string `xml:"source,attr"` 27 Path string `xml:"path,attr"` 28 } `xml:"alias"` 29 Def *struct { 30 Common 31 Choice string `xml:"choice,attr,omitempty"` 32 Type string `xml:"type,attr,omitempty"` 33 } `xml:"default"` 34} 35 36// Common holds several of the most common attributes and sub elements 37// of an XML element. 38type Common struct { 39 XMLName xml.Name 40 name string 41 enclElem Elem 42 Type string `xml:"type,attr,omitempty"` 43 Reference string `xml:"reference,attr,omitempty"` 44 Alt string `xml:"alt,attr,omitempty"` 45 ValidSubLocales string `xml:"validSubLocales,attr,omitempty"` 46 Draft string `xml:"draft,attr,omitempty"` 47 hidden 48} 49 50// Default returns the default type to select from the enclosed list 51// or "" if no default value is specified. 52func (e *Common) Default() string { 53 if e.Def == nil { 54 return "" 55 } 56 if e.Def.Choice != "" { 57 return e.Def.Choice 58 } else if e.Def.Type != "" { 59 // Type is still used by the default element in collation. 60 return e.Def.Type 61 } 62 return "" 63} 64 65// Element returns the XML element name. 66func (e *Common) Element() string { 67 return e.name 68} 69 70// GetCommon returns e. It is provided such that Common implements Elem. 71func (e *Common) GetCommon() *Common { 72 return e 73} 74 75// Data returns the character data accumulated for this element. 76func (e *Common) Data() string { 77 e.CharData = charRe.ReplaceAllStringFunc(e.CharData, replaceUnicode) 78 return e.CharData 79} 80 81func (e *Common) setName(s string) { 82 e.name = s 83} 84 85func (e *Common) enclosing() Elem { 86 return e.enclElem 87} 88 89func (e *Common) setEnclosing(en Elem) { 90 e.enclElem = en 91} 92 93// Escape characters that can be escaped without further escaping the string. 94var charRe = regexp.MustCompile(`&#x[0-9a-fA-F]*;|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\x[0-9a-fA-F]{2}|\\[0-7]{3}|\\[abtnvfr]`) 95 96// replaceUnicode converts hexadecimal Unicode codepoint notations to a one-rune string. 97// It assumes the input string is correctly formatted. 98func replaceUnicode(s string) string { 99 if s[1] == '#' { 100 r, _ := strconv.ParseInt(s[3:len(s)-1], 16, 32) 101 return string(r) 102 } 103 r, _, _, _ := strconv.UnquoteChar(s, 0) 104 return string(r) 105} 106