//ParseHmtx parse hmtx table  https://www.microsoft.com/typography/otspec/hmtx.htm
187120
func (t *TTFParser) ParseHmtx(fd *bytes.Reader) error {

	t.Seek(fd, "hmtx")
	i := uint(0)
	for i < t.numberOfHMetrics {
		advanceWidth, err := t.ReadUShort(fd)
		if err != nil {
			return err
		}
		err = t.Skip(fd, 2)
		if err != nil {
			return err
		}
		t.widths = append(t.widths, advanceWidth)
		i++
	}
	if t.numberOfHMetrics < t.numGlyphs {
		var err error
		lastWidth := t.widths[t.numberOfHMetrics-1]
		t.widths, err = t.ArrayPadUint(t.widths, t.numGlyphs, lastWidth)
		if err != nil {
			return err
		}
	}

	return nil
}
1151630
func (t *tree) parseMsgRawText(node *ast.RawTextNode) []ast.Node {
	var (
		r   []ast.Node
		txt = node.Text
		pos = node.Position()
	)
	for len(txt) > 0 {
		var start, end = len(txt), len(txt)
		var ii = htmlTagRegexp.FindSubmatchIndex(txt)
		if ii != nil {
			start, end = ii[0], ii[1]
		}

		if start > 0 {
			r = append(r, &ast.RawTextNode{pos, txt[:start]})
			pos += ast.Pos(start)
		}

		if end > start {
			r = append(r, &ast.MsgPlaceholderNode{pos, "", &ast.MsgHtmlTagNode{pos, txt[start:end]}})
			pos += ast.Pos(end - start)
		}

		txt = txt[end:]
	}
	return r
}
52811
func parseHTPasswd(rd io.Reader) (map[string][]byte, error) {
	entries := map[string][]byte{}
	scanner := bufio.NewScanner(rd)
	var line int
	for scanner.Scan() {
		line++ // 1-based line numbering
		t := strings.TrimSpace(scanner.Text())

		if len(t) < 1 {
			continue
		}

		// lines that *begin* with a '#' are considered comments
		if t[0] == '#' {
			continue
		}

		i := strings.Index(t, ":")
		if i < 0 || i >= len(t) {
			return nil, fmt.Errorf("htpasswd: invalid entry at line %d: %q", line, scanner.Text())
		}

		entries[t[:i]] = []byte(t[i+1:])
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return entries, nil
}
1181795
func parsePrefix(s string) (string, string) {
	if strings.HasPrefix(s, "P") {
		return "P", s[1:]
	}
	if len(s) < 2 {
		return s, ""
	}
	return s[:2], s[2:]
}
1266199
func (t *Trie) MatchPrefix(view []byte) string {
	for t != nil {
		if len(t.label) != 0 {
			return t.label
		}

		if len(view) == 0 {
			break
		}

		t = t.children[view[0]]
		view = view[1:]
	}

	return ""
}
323241
func HeaderMatch(hdr http.Header, nm string, matchType HeaderMatchType, test string) bool {
	// First get the header value
	val := hdr[http.CanonicalHeaderKey(nm)]
	if len(val) == 0 {
		return false
	}
	// Prepare the match test
	test = strings.ToLower(test)
	for _, v := range val {
		v = strings.Trim(strings.ToLower(v), " \n\t")
		switch matchType {
		case HmEquals:
			if v == test {
				return true
			}
		case HmStartsWith:
			if strings.HasPrefix(v, test) {
				return true
			}
		case HmEndsWith:
			if strings.HasSuffix(v, test) {
				return true
			}
		case HmContains:
			if strings.Contains(v, test) {
				return true
			}
		}
	}
	return false
}
926739
func ParseHeaders(
	hdrTraceID, hdrSpanID, hdrParentSpanID, hdrSampled, hdrFlags string,
) (*model.SpanContext, error) {
	var (
		err           error
		spanID        uint64
		requiredCount int
		sc            = &model.SpanContext{}
	)

	// correct values for an existing sampled header are "0" and "1".
	// For legacy support and  being lenient to other tracing implementations we
	// allow "true" and "false" as inputs for interop purposes.
	switch strings.ToLower(hdrSampled) {
	case "0", "false":
		sampled := false
		sc.Sampled = &sampled
	case "1", "true":
		sampled := true
		sc.Sampled = &sampled
	case "":
		// sc.Sampled = nil
	default:
		return nil, ErrInvalidSampledHeader
	}

	// The only accepted value for Flags is "1". This will set Debug to true. All
	// other values and omission of header will be ignored.
	if hdrFlags == "1" {
		sc.Debug = true
		sc.Sampled = nil
	}

	if hdrTraceID != "" {
		requiredCount++
		if sc.TraceID, err = model.TraceIDFromHex(hdrTraceID); err != nil {
			return nil, ErrInvalidTraceIDHeader
		}
	}

	if hdrSpanID != "" {
		requiredCount++
		if spanID, err = strconv.ParseUint(hdrSpanID, 16, 64); err != nil {
			return nil, ErrInvalidSpanIDHeader
		}
		sc.ID = model.ID(spanID)
	}

	if requiredCount != 0 && requiredCount != 2 {
		return nil, ErrInvalidScope
	}

	if hdrParentSpanID != "" {
		if requiredCount == 0 {
			return nil, ErrInvalidScopeParent
		}
		if spanID, err = strconv.ParseUint(hdrParentSpanID, 16, 64); err != nil {
			return nil, ErrInvalidParentSpanIDHeader
		}
		parentSpanID := model.ID(spanID)
		sc.ParentID = &parentSpanID
	}

	return sc, nil
}
533404
func (m *Model) ParseModel(modelName string, currentPackage string, knownModelNames map[string]bool) (error, []*Model) {
	knownModelNames[modelName] = true
	//log.Printf("Before parse model |%s|, package: |%s|\n", modelName, currentPackage)

	astTypeSpec, modelPackage := m.parser.FindModelDefinition(modelName, currentPackage)

	modelNameParts := strings.Split(modelName, ".")
	m.Id = strings.Join(append(strings.Split(modelPackage, "/"), modelNameParts[len(modelNameParts)-1]), ".")

	var innerModelList []*Model
	if astTypeDef, ok := astTypeSpec.Type.(*ast.Ident); ok {
		typeDefTranslations[astTypeSpec.Name.String()] = astTypeDef.Name
	} else if astStructType, ok := astTypeSpec.Type.(*ast.StructType); ok {
		m.ParseFieldList(astStructType.Fields.List, modelPackage)
		usedTypes := make(map[string]bool)

		for _, property := range m.Properties {
			typeName := property.Type
			if typeName == "array" {
				if property.Items.Type != "" {
					typeName = property.Items.Type
				} else {
					typeName = property.Items.Ref
				}
			}
			if translation, ok := typeDefTranslations[typeName]; ok {
				typeName = translation
			}
			if IsBasicType(typeName) || m.parser.IsImplementMarshalInterface(typeName) {
				continue
			}
			if _, exists := knownModelNames[typeName]; exists {
				continue
			}

			usedTypes[typeName] = true
		}

		//log.Printf("Before parse inner model list: %#v\n (%s)", usedTypes, modelName)
		innerModelList = make([]*Model, 0, len(usedTypes))

		for typeName, _ := range usedTypes {
			typeModel := NewModel(m.parser)
			if err, typeInnerModels := typeModel.ParseModel(typeName, modelPackage, knownModelNames); err != nil {
				//log.Printf("Parse Inner Model error %#v \n", err)
				return err, nil
			} else {
				for _, property := range m.Properties {
					if property.Type == "array" {
						if property.Items.Ref == typeName {
							property.Items.Ref = typeModel.Id
						}
					} else {
						if property.Type == typeName {
							property.Type = typeModel.Id
						}
					}
				}
				//log.Printf("Inner model %v parsed, parsing %s \n", typeName, modelName)
				if typeModel != nil {
					innerModelList = append(innerModelList, typeModel)
				}
				if typeInnerModels != nil && len(typeInnerModels) > 0 {
					innerModelList = append(innerModelList, typeInnerModels...)
				}
				//log.Printf("innerModelList: %#v\n, typeInnerModels: %#v, usedTypes: %#v \n", innerModelList, typeInnerModels, usedTypes)
			}
		}
		//log.Printf("After parse inner model list: %#v\n (%s)", usedTypes, modelName)
		// log.Fatalf("Inner model list: %#v\n", innerModelList)

	}

	//log.Printf("ParseModel finished %s \n", modelName)
	return nil, innerModelList
}
686041
func ParseStmt(stmt string) (ast.Stmt, error) {
	// parser.ParseExpr has some quirks, for example it won't parse unused map literals as
	// ExprStmts. Unused map literals are technically illegal, but it would be
	// nice to check them at a later stage. Therefore, we want to parse expressions
	// as expressions, and stmts and stmts. We try both.
	// However, there is a bug in parser.ParseExpr that it does not detect excess input.
	// Therefore, the _ of _ = 1 will be parsed as an expression. To avoid this, attempt
	// to parse the input as a statement first, and fall back to an expression
	expr := "func(){" + stmt + ";}"
	if e, err := parser.ParseExpr(expr); err != nil {
		if e, err := parser.ParseExpr(stmt); err == nil {
			return &ast.ExprStmt{X: e}, nil
		}
		errs := err.(scanner.ErrorList)
		for i := range errs {
			errs[i].Pos.Offset -= 7
			errs[i].Pos.Column -= 7
		}
		return nil, errs
	} else {
		node := e.(*ast.FuncLit).Body.List[0]
		if stmt, ok := node.(Stmt); !ok {
			return nil, fmt.Errorf("%T not supported", node)
		} else {
			return stmt, nil
		}
	}
}
160335
func (t *dbTables) parseExprs(mi *modelInfo, exprs []string) (index, name string, info *fieldInfo, success bool) {
	var (
		jtl *dbTable
		fi  *fieldInfo
		fiN *fieldInfo
		mmi = mi
	)

	num := len(exprs) - 1
	var names []string

	inner := true

loopFor:
	for i, ex := range exprs {

		var ok, okN bool

		if fiN != nil {
			fi = fiN
			ok = true
			fiN = nil
		}

		if i == 0 {
			fi, ok = mmi.fields.GetByAny(ex)
		}

		_ = okN

		if ok {

			isRel := fi.rel || fi.reverse

			names = append(names, fi.name)

			switch {
			case fi.rel:
				mmi = fi.relModelInfo
				if fi.fieldType == RelManyToMany {
					mmi = fi.relThroughModelInfo
				}
			case fi.reverse:
				mmi = fi.reverseFieldInfo.mi
			}

			if i < num {
				fiN, okN = mmi.fields.GetByAny(exprs[i+1])
			}

			if isRel && (fi.mi.isThrough == false || num != i) {
				if fi.null || t.skipEnd {
					inner = false
				}

				if t.skipEnd && okN || !t.skipEnd {
					if t.skipEnd && okN && fiN.pk {
						goto loopEnd
					}

					jt, _ := t.add(names, mmi, fi, inner)
					jt.jtl = jtl
					jtl = jt
				}

			}

			if num != i {
				continue
			}

		loopEnd:

			if i == 0 || jtl == nil {
				index = "T0"
			} else {
				index = jtl.index
			}

			info = fi

			if jtl == nil {
				name = fi.name
			} else {
				name = jtl.name + ExprSep + fi.name
			}

			switch {
			case fi.rel:

			case fi.reverse:
				switch fi.reverseFieldInfo.fieldType {
				case RelOneToOne, RelForeignKey:
					index = jtl.index
					info = fi.reverseFieldInfo.mi.fields.pk
					name = info.name
				}
			}

			break loopFor

		} else {
			index = ""
			name = ""
			info = nil
			success = false
			return
		}
	}

	success = index != "" && info != nil
	return
}
41100
func (inliner *Inliner) parseHTML() error {
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(inliner.html))
	if err != nil {
		return err
	}

	inliner.doc = doc

	return nil
}
97149
func ParseHEX(input string, length int) ([]byte, error) {
	if input == "" {
		return make([]byte, length), nil
	}

	pattern := regexp.MustCompile(fmt.Sprintf("^[[:xdigit:]]{%d}$", length*2))

	valid := pattern.MatchString(input)
	if !valid {
		return nil, fmt.Errorf("Invalid input: %s is not hex", input)
	}

	slice, _ := hex.DecodeString(input)

	return slice, nil
}
745275
func (inliner *Inliner) parseStylesheets() error {
	var result error

	inliner.doc.Find("style").EachWithBreak(func(i int, s *goquery.Selection) bool {
		stylesheet, err := parser.Parse(s.Text())
		if err != nil {
			result = err
			return false
		}

		inliner.stylesheets = append(inliner.stylesheets, stylesheet)

		// removes parsed stylesheet
		s.Remove()

		return true
	})

	return result
}
324286
func parseXlog(x xlog.Position) (pos int64, err error) {
	if x == "" {
		return 0, nil
	}
	parts := strings.SplitN(string(x), "-", 3)
	if len(parts) != 3 {
		err = fmt.Errorf("malformed xlog position %q", x)
		return
	}

	pos, err = strconv.ParseInt(parts[2], 10, 64)
	if err != nil {
		return 0, err
	}

	return pos, err
}
113790
func ParseZoom(zoom string) ZoomLevel {
	switch ZoomLevel(zoom) {
	case BlockZoom:
		return BlockZoom
	case WindowZoom:
		return WindowZoom
	}
	return DefaultZoomLevel
}
174192
func (t *Table) SetHTMLStyleTitle(want titleStyle) {
	t.Style.htmlRules.title = want
}
1078363
func (po *Po) parseMessage(l string) {
	l = strings.TrimSpace(strings.TrimPrefix(l, "msgstr"))

	// Check for indexed Translation forms
	if strings.HasPrefix(l, "[") {
		idx := strings.Index(l, "]")
		if idx == -1 {
			// Skip wrong index formatting
			return
		}

		// Parse index
		i, err := strconv.Atoi(l[1:idx])
		if err != nil {
			// Skip wrong index formatting
			return
		}

		// Parse Translation string
		po.trBuffer.Trs[i], _ = strconv.Unquote(strings.TrimSpace(l[idx+1:]))

		// Loop
		return
	}

	// Save single Translation form under 0 index
	po.trBuffer.Trs[0], _ = strconv.Unquote(l)
}