From d90024b17b59ee9b3e1668aa5ef13e45e0bad782 Mon Sep 17 00:00:00 2001 From: Tw Date: Wed, 11 Feb 2015 14:59:40 +0800 Subject: [PATCH] Delete unnecessary copy of input when enable fenced code extension Copy of input waste time and memory. Signed-off-by: Tw --- block.go | 29 ++++++++++++++++++++--------- markdown.go | 5 +---- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/block.go b/block.go index 9b00320..59c6d28 100644 --- a/block.go +++ b/block.go @@ -556,9 +556,12 @@ func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (s skip = 0 // skip up to three spaces - for i < 3 && data[i] == ' ' { + for i < len(data) && i < 3 && data[i] == ' ' { i++ } + if i >= len(data) { + return + } // check for the marker characters: ~ or ` if data[i] != '~' && data[i] != '`' { @@ -568,11 +571,15 @@ func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (s c := data[i] // the whole line must be the same char or whitespace - for data[i] == c { + for i < len(data) && data[i] == c { size++ i++ } + if i >= len(data) { + return + } + // the marker char must occur at least 3 times if size < 3 { return @@ -587,22 +594,26 @@ func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (s if syntax != nil { syn := 0 - for data[i] == ' ' { + for i < len(data) && data[i] == ' ' { i++ } + if i >= len(data) { + return + } + syntaxStart := i if data[i] == '{' { i++ syntaxStart++ - for data[i] != '}' && data[i] != '\n' { + for i < len(data) && data[i] != '}' && data[i] != '\n' { syn++ i++ } - if data[i] != '}' { + if i >= len(data) || data[i] != '}' { return } @@ -619,7 +630,7 @@ func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (s i++ } else { - for !isspace(data[i]) { + for i < len(data) && !isspace(data[i]) { syn++ i++ } @@ -629,10 +640,10 @@ func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (s *syntax = &language } - for data[i] == ' ' { + for i < len(data) && data[i] == ' ' { i++ } - if data[i] != '\n' { + if i >= len(data) || data[i] != '\n' { return } @@ -661,7 +672,7 @@ func (p *parser) fencedCode(out *bytes.Buffer, data []byte, doRender bool) int { // copy the current line end := beg - for data[end] != '\n' { + for end < len(data) && data[end] != '\n' { end++ } end++ diff --git a/markdown.go b/markdown.go index d07e37c..4315488 100644 --- a/markdown.go +++ b/markdown.go @@ -327,10 +327,7 @@ func firstPass(p *parser, input []byte) []byte { if p.flags&EXTENSION_FENCED_CODE != 0 { // when last line was none blank and a fenced code block comes after if beg >= lastFencedCodeBlockEnd { - // tmp var so we don't modify beyond bounds of `input` - var tmp = make([]byte, len(input[beg:]), len(input[beg:])+1) - copy(tmp, input[beg:]) - if i := p.fencedCode(&out, append(tmp, '\n'), false); i > 0 { + if i := p.fencedCode(&out, input[beg:], false); i > 0 { if !lastLineWasBlank { out.WriteByte('\n') // need to inject additional linebreak }