Skip to content

Commit bec27a4

Browse files
fancycodehhrutter
authored andcommitted
Avoid calling "DecodeName" when parsing dictionaries.
If no name with a "#" has been added before, it's not necessary to go through the expensive "Insert" call that will call "DecodeName" for every previously added key.
1 parent b89d7b1 commit bec27a4

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

pkg/pdfcpu/model/parse.go

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,7 @@ func parseName(line *string) (*types.Name, error) {
530530
func processDictKeys(line *string, relaxed bool) (types.Dict, error) {
531531
l := *line
532532
var eol bool
533+
var hasNames bool
533534
d := types.NewDict()
534535
for !strings.HasPrefix(l, ">>") {
535536
key, err := parseName(&l)
@@ -558,8 +559,18 @@ func processDictKeys(line *string, relaxed bool) (types.Dict, error) {
558559
if log.ParseEnabled() {
559560
log.Parse.Printf("ParseDict: dict[%s]=%v\n", key, obj)
560561
}
561-
if ok := d.Insert(string(*key), obj); !ok {
562-
return nil, errDictionaryDuplicateKey
562+
stringKey := string(*key)
563+
if !hasNames {
564+
// Avoid expensive "DecodeName" on existing keys in "Insert".
565+
if _, found := d[stringKey]; found {
566+
return nil, errDictionaryDuplicateKey
567+
}
568+
d[stringKey] = obj
569+
hasNames = strings.IndexByte(stringKey, '#') >= 0
570+
} else {
571+
if ok := d.Insert(stringKey, obj); !ok {
572+
return nil, errDictionaryDuplicateKey
573+
}
563574
}
564575
continue
565576
}
@@ -572,7 +583,16 @@ func processDictKeys(line *string, relaxed bool) (types.Dict, error) {
572583
// Specifying the null object as the value of a dictionary entry (7.3.7, "Dictionary Objects")
573584
// hall be equivalent to omitting the entry entirely.
574585
if obj != nil {
575-
d.Insert(string(*key), obj)
586+
stringKey := string(*key)
587+
if !hasNames {
588+
// Avoid expensive "DecodeName" on existing keys in "Insert".
589+
if _, found := d[stringKey]; !found {
590+
d[stringKey] = obj
591+
hasNames = strings.IndexByte(stringKey, '#') >= 0
592+
}
593+
} else {
594+
d.Insert(stringKey, obj)
595+
}
576596
if log.ParseEnabled() {
577597
log.Parse.Printf("ParseDict: dict[%s]=%v\n", key, obj)
578598
}

0 commit comments

Comments
 (0)