repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
jhillyerd/enmime
envelope.go
parseMultiPartBody
func parseMultiPartBody(root *Part, e *Envelope) error { // Parse top-level multipart ctype := root.Header.Get(hnContentType) mediatype, params, _, err := parseMediaType(ctype) if err != nil { return fmt.Errorf("Unable to parse media type: %v", err) } if !strings.HasPrefix(mediatype, ctMultipartPrefix) { return fmt.Errorf("Unknown mediatype: %v", mediatype) } boundary := params[hpBoundary] if boundary == "" { return fmt.Errorf("Unable to locate boundary param in Content-Type header") } // Locate text body if mediatype == ctMultipartAltern { p := root.BreadthMatchFirst(func(p *Part) bool { return p.ContentType == ctTextPlain && p.Disposition != cdAttachment }) if p != nil { e.Text = string(p.Content) } } else { // multipart is of a mixed type parts := root.DepthMatchAll(func(p *Part) bool { return p.ContentType == ctTextPlain && p.Disposition != cdAttachment }) for i, p := range parts { if i > 0 { e.Text += "\n--\n" } e.Text += string(p.Content) } } // Locate HTML body p := root.BreadthMatchFirst(matchHTMLBodyPart) if p != nil { e.HTML += string(p.Content) } // Locate attachments e.Attachments = root.BreadthMatchAll(func(p *Part) bool { return p.Disposition == cdAttachment || p.ContentType == ctAppOctetStream }) // Locate inlines e.Inlines = root.BreadthMatchAll(func(p *Part) bool { return p.Disposition == cdInline && !strings.HasPrefix(p.ContentType, ctMultipartPrefix) }) // Locate others parts not considered in attachments or inlines e.OtherParts = root.BreadthMatchAll(func(p *Part) bool { if strings.HasPrefix(p.ContentType, ctMultipartPrefix) { return false } if p.Disposition != "" { return false } if p.ContentType == ctAppOctetStream { return false } return p.ContentType != ctTextPlain && p.ContentType != ctTextHTML }) return nil }
go
func parseMultiPartBody(root *Part, e *Envelope) error { // Parse top-level multipart ctype := root.Header.Get(hnContentType) mediatype, params, _, err := parseMediaType(ctype) if err != nil { return fmt.Errorf("Unable to parse media type: %v", err) } if !strings.HasPrefix(mediatype, ctMultipartPrefix) { return fmt.Errorf("Unknown mediatype: %v", mediatype) } boundary := params[hpBoundary] if boundary == "" { return fmt.Errorf("Unable to locate boundary param in Content-Type header") } // Locate text body if mediatype == ctMultipartAltern { p := root.BreadthMatchFirst(func(p *Part) bool { return p.ContentType == ctTextPlain && p.Disposition != cdAttachment }) if p != nil { e.Text = string(p.Content) } } else { // multipart is of a mixed type parts := root.DepthMatchAll(func(p *Part) bool { return p.ContentType == ctTextPlain && p.Disposition != cdAttachment }) for i, p := range parts { if i > 0 { e.Text += "\n--\n" } e.Text += string(p.Content) } } // Locate HTML body p := root.BreadthMatchFirst(matchHTMLBodyPart) if p != nil { e.HTML += string(p.Content) } // Locate attachments e.Attachments = root.BreadthMatchAll(func(p *Part) bool { return p.Disposition == cdAttachment || p.ContentType == ctAppOctetStream }) // Locate inlines e.Inlines = root.BreadthMatchAll(func(p *Part) bool { return p.Disposition == cdInline && !strings.HasPrefix(p.ContentType, ctMultipartPrefix) }) // Locate others parts not considered in attachments or inlines e.OtherParts = root.BreadthMatchAll(func(p *Part) bool { if strings.HasPrefix(p.ContentType, ctMultipartPrefix) { return false } if p.Disposition != "" { return false } if p.ContentType == ctAppOctetStream { return false } return p.ContentType != ctTextPlain && p.ContentType != ctTextHTML }) return nil }
[ "func", "parseMultiPartBody", "(", "root", "*", "Part", ",", "e", "*", "Envelope", ")", "error", "{", "ctype", ":=", "root", ".", "Header", ".", "Get", "(", "hnContentType", ")", "\n", "mediatype", ",", "params", ",", "_", ",", "err", ":=", "parseMediaType", "(", "ctype", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Unable to parse media type: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "mediatype", ",", "ctMultipartPrefix", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"Unknown mediatype: %v\"", ",", "mediatype", ")", "\n", "}", "\n", "boundary", ":=", "params", "[", "hpBoundary", "]", "\n", "if", "boundary", "==", "\"\"", "{", "return", "fmt", ".", "Errorf", "(", "\"Unable to locate boundary param in Content-Type header\"", ")", "\n", "}", "\n", "if", "mediatype", "==", "ctMultipartAltern", "{", "p", ":=", "root", ".", "BreadthMatchFirst", "(", "func", "(", "p", "*", "Part", ")", "bool", "{", "return", "p", ".", "ContentType", "==", "ctTextPlain", "&&", "p", ".", "Disposition", "!=", "cdAttachment", "\n", "}", ")", "\n", "if", "p", "!=", "nil", "{", "e", ".", "Text", "=", "string", "(", "p", ".", "Content", ")", "\n", "}", "\n", "}", "else", "{", "parts", ":=", "root", ".", "DepthMatchAll", "(", "func", "(", "p", "*", "Part", ")", "bool", "{", "return", "p", ".", "ContentType", "==", "ctTextPlain", "&&", "p", ".", "Disposition", "!=", "cdAttachment", "\n", "}", ")", "\n", "for", "i", ",", "p", ":=", "range", "parts", "{", "if", "i", ">", "0", "{", "e", ".", "Text", "+=", "\"\\n--\\n\"", "\n", "}", "\n", "\\n", "\n", "}", "\n", "}", "\n", "\\n", "\n", "e", ".", "Text", "+=", "string", "(", "p", ".", "Content", ")", "\n", "p", ":=", "root", ".", "BreadthMatchFirst", "(", "matchHTMLBodyPart", ")", "\n", "if", "p", "!=", "nil", "{", "e", ".", "HTML", "+=", "string", "(", "p", ".", "Content", ")", "\n", "}", "\n", "e", ".", "Attachments", "=", "root", ".", "BreadthMatchAll", "(", "func", "(", "p", "*", "Part", ")", "bool", "{", "return", "p", ".", "Disposition", "==", "cdAttachment", "||", "p", ".", "ContentType", "==", "ctAppOctetStream", "\n", "}", ")", "\n", "e", ".", "Inlines", "=", "root", ".", "BreadthMatchAll", "(", "func", "(", "p", "*", "Part", ")", "bool", "{", "return", "p", ".", "Disposition", "==", "cdInline", "&&", "!", "strings", ".", "HasPrefix", "(", "p", ".", "ContentType", ",", "ctMultipartPrefix", ")", "\n", "}", ")", "\n", "}" ]
// parseMultiPartBody parses a multipart message in root. The result is placed in e.
[ "parseMultiPartBody", "parses", "a", "multipart", "message", "in", "root", ".", "The", "result", "is", "placed", "in", "e", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L275-L342
test
jhillyerd/enmime
envelope.go
matchHTMLBodyPart
func matchHTMLBodyPart(p *Part) bool { return p.ContentType == ctTextHTML && p.Disposition != cdAttachment }
go
func matchHTMLBodyPart(p *Part) bool { return p.ContentType == ctTextHTML && p.Disposition != cdAttachment }
[ "func", "matchHTMLBodyPart", "(", "p", "*", "Part", ")", "bool", "{", "return", "p", ".", "ContentType", "==", "ctTextHTML", "&&", "p", ".", "Disposition", "!=", "cdAttachment", "\n", "}" ]
// Used by Part matchers to locate the HTML body. Not inlined because it's used in multiple places.
[ "Used", "by", "Part", "matchers", "to", "locate", "the", "HTML", "body", ".", "Not", "inlined", "because", "it", "s", "used", "in", "multiple", "places", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L345-L347
test
jhillyerd/enmime
envelope.go
ensureCommaDelimitedAddresses
func ensureCommaDelimitedAddresses(s string) string { // This normalizes the whitespace, but may interfere with CFWS (comments with folding whitespace) // RFC-5322 3.4.0: // because some legacy implementations interpret the comment, // comments generally SHOULD NOT be used in address fields // to avoid confusing such implementations. s = strings.Join(strings.Fields(s), " ") inQuotes := false inDomain := false escapeSequence := false sb := strings.Builder{} for _, r := range s { if escapeSequence { escapeSequence = false sb.WriteRune(r) continue } if r == '"' { inQuotes = !inQuotes sb.WriteRune(r) continue } if inQuotes { if r == '\\' { escapeSequence = true sb.WriteRune(r) continue } } else { if r == '@' { inDomain = true sb.WriteRune(r) continue } if inDomain { if r == ';' { sb.WriteRune(r) break } if r == ',' { inDomain = false sb.WriteRune(r) continue } if r == ' ' { inDomain = false sb.WriteRune(',') sb.WriteRune(r) continue } } } sb.WriteRune(r) } return sb.String() }
go
func ensureCommaDelimitedAddresses(s string) string { // This normalizes the whitespace, but may interfere with CFWS (comments with folding whitespace) // RFC-5322 3.4.0: // because some legacy implementations interpret the comment, // comments generally SHOULD NOT be used in address fields // to avoid confusing such implementations. s = strings.Join(strings.Fields(s), " ") inQuotes := false inDomain := false escapeSequence := false sb := strings.Builder{} for _, r := range s { if escapeSequence { escapeSequence = false sb.WriteRune(r) continue } if r == '"' { inQuotes = !inQuotes sb.WriteRune(r) continue } if inQuotes { if r == '\\' { escapeSequence = true sb.WriteRune(r) continue } } else { if r == '@' { inDomain = true sb.WriteRune(r) continue } if inDomain { if r == ';' { sb.WriteRune(r) break } if r == ',' { inDomain = false sb.WriteRune(r) continue } if r == ' ' { inDomain = false sb.WriteRune(',') sb.WriteRune(r) continue } } } sb.WriteRune(r) } return sb.String() }
[ "func", "ensureCommaDelimitedAddresses", "(", "s", "string", ")", "string", "{", "s", "=", "strings", ".", "Join", "(", "strings", ".", "Fields", "(", "s", ")", ",", "\" \"", ")", "\n", "inQuotes", ":=", "false", "\n", "inDomain", ":=", "false", "\n", "escapeSequence", ":=", "false", "\n", "sb", ":=", "strings", ".", "Builder", "{", "}", "\n", "for", "_", ",", "r", ":=", "range", "s", "{", "if", "escapeSequence", "{", "escapeSequence", "=", "false", "\n", "sb", ".", "WriteRune", "(", "r", ")", "\n", "continue", "\n", "}", "\n", "if", "r", "==", "'\"'", "{", "inQuotes", "=", "!", "inQuotes", "\n", "sb", ".", "WriteRune", "(", "r", ")", "\n", "continue", "\n", "}", "\n", "if", "inQuotes", "{", "if", "r", "==", "'\\\\'", "{", "escapeSequence", "=", "true", "\n", "sb", ".", "WriteRune", "(", "r", ")", "\n", "continue", "\n", "}", "\n", "}", "else", "{", "if", "r", "==", "'@'", "{", "inDomain", "=", "true", "\n", "sb", ".", "WriteRune", "(", "r", ")", "\n", "continue", "\n", "}", "\n", "if", "inDomain", "{", "if", "r", "==", "';'", "{", "sb", ".", "WriteRune", "(", "r", ")", "\n", "break", "\n", "}", "\n", "if", "r", "==", "','", "{", "inDomain", "=", "false", "\n", "sb", ".", "WriteRune", "(", "r", ")", "\n", "continue", "\n", "}", "\n", "if", "r", "==", "' '", "{", "inDomain", "=", "false", "\n", "sb", ".", "WriteRune", "(", "','", ")", "\n", "sb", ".", "WriteRune", "(", "r", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "}", "\n", "sb", ".", "WriteRune", "(", "r", ")", "\n", "}", "\n", "return", "sb", ".", "String", "(", ")", "\n", "}" ]
// Used by AddressList to ensure that address lists are properly delimited
[ "Used", "by", "AddressList", "to", "ensure", "that", "address", "lists", "are", "properly", "delimited" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L350-L406
test
jhillyerd/enmime
builder.go
Date
func (p MailBuilder) Date(date time.Time) MailBuilder { p.date = date return p }
go
func (p MailBuilder) Date(date time.Time) MailBuilder { p.date = date return p }
[ "func", "(", "p", "MailBuilder", ")", "Date", "(", "date", "time", ".", "Time", ")", "MailBuilder", "{", "p", ".", "date", "=", "date", "\n", "return", "p", "\n", "}" ]
// Date returns a copy of MailBuilder with the specified Date header.
[ "Date", "returns", "a", "copy", "of", "MailBuilder", "with", "the", "specified", "Date", "header", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L46-L49
test
jhillyerd/enmime
builder.go
From
func (p MailBuilder) From(name, addr string) MailBuilder { p.from = mail.Address{Name: name, Address: addr} return p }
go
func (p MailBuilder) From(name, addr string) MailBuilder { p.from = mail.Address{Name: name, Address: addr} return p }
[ "func", "(", "p", "MailBuilder", ")", "From", "(", "name", ",", "addr", "string", ")", "MailBuilder", "{", "p", ".", "from", "=", "mail", ".", "Address", "{", "Name", ":", "name", ",", "Address", ":", "addr", "}", "\n", "return", "p", "\n", "}" ]
// From returns a copy of MailBuilder with the specified From header.
[ "From", "returns", "a", "copy", "of", "MailBuilder", "with", "the", "specified", "From", "header", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L52-L55
test
jhillyerd/enmime
builder.go
Subject
func (p MailBuilder) Subject(subject string) MailBuilder { p.subject = subject return p }
go
func (p MailBuilder) Subject(subject string) MailBuilder { p.subject = subject return p }
[ "func", "(", "p", "MailBuilder", ")", "Subject", "(", "subject", "string", ")", "MailBuilder", "{", "p", ".", "subject", "=", "subject", "\n", "return", "p", "\n", "}" ]
// Subject returns a copy of MailBuilder with the specified Subject header.
[ "Subject", "returns", "a", "copy", "of", "MailBuilder", "with", "the", "specified", "Subject", "header", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L58-L61
test
jhillyerd/enmime
builder.go
To
func (p MailBuilder) To(name, addr string) MailBuilder { p.to = append(p.to, mail.Address{Name: name, Address: addr}) return p }
go
func (p MailBuilder) To(name, addr string) MailBuilder { p.to = append(p.to, mail.Address{Name: name, Address: addr}) return p }
[ "func", "(", "p", "MailBuilder", ")", "To", "(", "name", ",", "addr", "string", ")", "MailBuilder", "{", "p", ".", "to", "=", "append", "(", "p", ".", "to", ",", "mail", ".", "Address", "{", "Name", ":", "name", ",", "Address", ":", "addr", "}", ")", "\n", "return", "p", "\n", "}" ]
// To returns a copy of MailBuilder with this name & address appended to the To header. name may be // empty.
[ "To", "returns", "a", "copy", "of", "MailBuilder", "with", "this", "name", "&", "address", "appended", "to", "the", "To", "header", ".", "name", "may", "be", "empty", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L65-L68
test
jhillyerd/enmime
builder.go
ToAddrs
func (p MailBuilder) ToAddrs(to []mail.Address) MailBuilder { p.to = to return p }
go
func (p MailBuilder) ToAddrs(to []mail.Address) MailBuilder { p.to = to return p }
[ "func", "(", "p", "MailBuilder", ")", "ToAddrs", "(", "to", "[", "]", "mail", ".", "Address", ")", "MailBuilder", "{", "p", ".", "to", "=", "to", "\n", "return", "p", "\n", "}" ]
// ToAddrs returns a copy of MailBuilder with the specified To addresses.
[ "ToAddrs", "returns", "a", "copy", "of", "MailBuilder", "with", "the", "specified", "To", "addresses", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L71-L74
test
jhillyerd/enmime
builder.go
CC
func (p MailBuilder) CC(name, addr string) MailBuilder { p.cc = append(p.cc, mail.Address{Name: name, Address: addr}) return p }
go
func (p MailBuilder) CC(name, addr string) MailBuilder { p.cc = append(p.cc, mail.Address{Name: name, Address: addr}) return p }
[ "func", "(", "p", "MailBuilder", ")", "CC", "(", "name", ",", "addr", "string", ")", "MailBuilder", "{", "p", ".", "cc", "=", "append", "(", "p", ".", "cc", ",", "mail", ".", "Address", "{", "Name", ":", "name", ",", "Address", ":", "addr", "}", ")", "\n", "return", "p", "\n", "}" ]
// CC returns a copy of MailBuilder with this name & address appended to the CC header. name may be // empty.
[ "CC", "returns", "a", "copy", "of", "MailBuilder", "with", "this", "name", "&", "address", "appended", "to", "the", "CC", "header", ".", "name", "may", "be", "empty", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L78-L81
test
jhillyerd/enmime
builder.go
CCAddrs
func (p MailBuilder) CCAddrs(cc []mail.Address) MailBuilder { p.cc = cc return p }
go
func (p MailBuilder) CCAddrs(cc []mail.Address) MailBuilder { p.cc = cc return p }
[ "func", "(", "p", "MailBuilder", ")", "CCAddrs", "(", "cc", "[", "]", "mail", ".", "Address", ")", "MailBuilder", "{", "p", ".", "cc", "=", "cc", "\n", "return", "p", "\n", "}" ]
// CCAddrs returns a copy of MailBuilder with the specified CC addresses.
[ "CCAddrs", "returns", "a", "copy", "of", "MailBuilder", "with", "the", "specified", "CC", "addresses", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L84-L87
test
jhillyerd/enmime
builder.go
ReplyTo
func (p MailBuilder) ReplyTo(name, addr string) MailBuilder { p.replyTo = mail.Address{Name: name, Address: addr} return p }
go
func (p MailBuilder) ReplyTo(name, addr string) MailBuilder { p.replyTo = mail.Address{Name: name, Address: addr} return p }
[ "func", "(", "p", "MailBuilder", ")", "ReplyTo", "(", "name", ",", "addr", "string", ")", "MailBuilder", "{", "p", ".", "replyTo", "=", "mail", ".", "Address", "{", "Name", ":", "name", ",", "Address", ":", "addr", "}", "\n", "return", "p", "\n", "}" ]
// ReplyTo returns a copy of MailBuilder with this name & address appended to the To header. name // may be empty.
[ "ReplyTo", "returns", "a", "copy", "of", "MailBuilder", "with", "this", "name", "&", "address", "appended", "to", "the", "To", "header", ".", "name", "may", "be", "empty", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L107-L110
test
jhillyerd/enmime
builder.go
Header
func (p MailBuilder) Header(name, value string) MailBuilder { // Copy existing header map h := textproto.MIMEHeader{} for k, v := range p.header { h[k] = v } h.Add(name, value) p.header = h return p }
go
func (p MailBuilder) Header(name, value string) MailBuilder { // Copy existing header map h := textproto.MIMEHeader{} for k, v := range p.header { h[k] = v } h.Add(name, value) p.header = h return p }
[ "func", "(", "p", "MailBuilder", ")", "Header", "(", "name", ",", "value", "string", ")", "MailBuilder", "{", "h", ":=", "textproto", ".", "MIMEHeader", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "p", ".", "header", "{", "h", "[", "k", "]", "=", "v", "\n", "}", "\n", "h", ".", "Add", "(", "name", ",", "value", ")", "\n", "p", ".", "header", "=", "h", "\n", "return", "p", "\n", "}" ]
// Header returns a copy of MailBuilder with the specified value added to the named header.
[ "Header", "returns", "a", "copy", "of", "MailBuilder", "with", "the", "specified", "value", "added", "to", "the", "named", "header", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L113-L122
test
jhillyerd/enmime
builder.go
AddAttachment
func (p MailBuilder) AddAttachment(b []byte, contentType string, fileName string) MailBuilder { part := NewPart(contentType) part.Content = b part.FileName = fileName part.Disposition = cdAttachment p.attachments = append(p.attachments, part) return p }
go
func (p MailBuilder) AddAttachment(b []byte, contentType string, fileName string) MailBuilder { part := NewPart(contentType) part.Content = b part.FileName = fileName part.Disposition = cdAttachment p.attachments = append(p.attachments, part) return p }
[ "func", "(", "p", "MailBuilder", ")", "AddAttachment", "(", "b", "[", "]", "byte", ",", "contentType", "string", ",", "fileName", "string", ")", "MailBuilder", "{", "part", ":=", "NewPart", "(", "contentType", ")", "\n", "part", ".", "Content", "=", "b", "\n", "part", ".", "FileName", "=", "fileName", "\n", "part", ".", "Disposition", "=", "cdAttachment", "\n", "p", ".", "attachments", "=", "append", "(", "p", ".", "attachments", ",", "part", ")", "\n", "return", "p", "\n", "}" ]
// AddAttachment returns a copy of MailBuilder that includes the specified attachment.
[ "AddAttachment", "returns", "a", "copy", "of", "MailBuilder", "that", "includes", "the", "specified", "attachment", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L137-L144
test
jhillyerd/enmime
builder.go
AddFileAttachment
func (p MailBuilder) AddFileAttachment(path string) MailBuilder { // Only allow first p.err value if p.err != nil { return p } f, err := os.Open(path) if err != nil { p.err = err return p } b, err := ioutil.ReadAll(f) if err != nil { p.err = err return p } name := filepath.Base(path) ctype := mime.TypeByExtension(filepath.Ext(name)) return p.AddAttachment(b, ctype, name) }
go
func (p MailBuilder) AddFileAttachment(path string) MailBuilder { // Only allow first p.err value if p.err != nil { return p } f, err := os.Open(path) if err != nil { p.err = err return p } b, err := ioutil.ReadAll(f) if err != nil { p.err = err return p } name := filepath.Base(path) ctype := mime.TypeByExtension(filepath.Ext(name)) return p.AddAttachment(b, ctype, name) }
[ "func", "(", "p", "MailBuilder", ")", "AddFileAttachment", "(", "path", "string", ")", "MailBuilder", "{", "if", "p", ".", "err", "!=", "nil", "{", "return", "p", "\n", "}", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "err", "=", "err", "\n", "return", "p", "\n", "}", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "err", "=", "err", "\n", "return", "p", "\n", "}", "\n", "name", ":=", "filepath", ".", "Base", "(", "path", ")", "\n", "ctype", ":=", "mime", ".", "TypeByExtension", "(", "filepath", ".", "Ext", "(", "name", ")", ")", "\n", "return", "p", ".", "AddAttachment", "(", "b", ",", "ctype", ",", "name", ")", "\n", "}" ]
// AddFileAttachment returns a copy of MailBuilder that includes the specified attachment. // fileName, will be populated from the base name of path. Content type will be detected from the // path extension.
[ "AddFileAttachment", "returns", "a", "copy", "of", "MailBuilder", "that", "includes", "the", "specified", "attachment", ".", "fileName", "will", "be", "populated", "from", "the", "base", "name", "of", "path", ".", "Content", "type", "will", "be", "detected", "from", "the", "path", "extension", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L149-L167
test
jhillyerd/enmime
builder.go
AddInline
func (p MailBuilder) AddInline( b []byte, contentType string, fileName string, contentID string, ) MailBuilder { part := NewPart(contentType) part.Content = b part.FileName = fileName part.Disposition = cdInline part.ContentID = contentID p.inlines = append(p.inlines, part) return p }
go
func (p MailBuilder) AddInline( b []byte, contentType string, fileName string, contentID string, ) MailBuilder { part := NewPart(contentType) part.Content = b part.FileName = fileName part.Disposition = cdInline part.ContentID = contentID p.inlines = append(p.inlines, part) return p }
[ "func", "(", "p", "MailBuilder", ")", "AddInline", "(", "b", "[", "]", "byte", ",", "contentType", "string", ",", "fileName", "string", ",", "contentID", "string", ",", ")", "MailBuilder", "{", "part", ":=", "NewPart", "(", "contentType", ")", "\n", "part", ".", "Content", "=", "b", "\n", "part", ".", "FileName", "=", "fileName", "\n", "part", ".", "Disposition", "=", "cdInline", "\n", "part", ".", "ContentID", "=", "contentID", "\n", "p", ".", "inlines", "=", "append", "(", "p", ".", "inlines", ",", "part", ")", "\n", "return", "p", "\n", "}" ]
// AddInline returns a copy of MailBuilder that includes the specified inline. fileName and // contentID may be left empty.
[ "AddInline", "returns", "a", "copy", "of", "MailBuilder", "that", "includes", "the", "specified", "inline", ".", "fileName", "and", "contentID", "may", "be", "left", "empty", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L171-L184
test
jhillyerd/enmime
builder.go
Equals
func (p MailBuilder) Equals(o MailBuilder) bool { return reflect.DeepEqual(p, o) }
go
func (p MailBuilder) Equals(o MailBuilder) bool { return reflect.DeepEqual(p, o) }
[ "func", "(", "p", "MailBuilder", ")", "Equals", "(", "o", "MailBuilder", ")", "bool", "{", "return", "reflect", ".", "DeepEqual", "(", "p", ",", "o", ")", "\n", "}" ]
// Equals uses the reflect package to test two MailBuilder structs for equality, primarily for unit // tests.
[ "Equals", "uses", "the", "reflect", "package", "to", "test", "two", "MailBuilder", "structs", "for", "equality", "primarily", "for", "unit", "tests", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L337-L339
test
jhillyerd/enmime
encode.go
Encode
func (p *Part) Encode(writer io.Writer) error { if p.Header == nil { p.Header = make(textproto.MIMEHeader) } cte := p.setupMIMEHeaders() // Encode this part. b := bufio.NewWriter(writer) p.encodeHeader(b) if len(p.Content) > 0 { b.Write(crnl) if err := p.encodeContent(b, cte); err != nil { return err } } if p.FirstChild == nil { return b.Flush() } // Encode children. endMarker := []byte("\r\n--" + p.Boundary + "--") marker := endMarker[:len(endMarker)-2] c := p.FirstChild for c != nil { b.Write(marker) b.Write(crnl) if err := c.Encode(b); err != nil { return err } c = c.NextSibling } b.Write(endMarker) b.Write(crnl) return b.Flush() }
go
func (p *Part) Encode(writer io.Writer) error { if p.Header == nil { p.Header = make(textproto.MIMEHeader) } cte := p.setupMIMEHeaders() // Encode this part. b := bufio.NewWriter(writer) p.encodeHeader(b) if len(p.Content) > 0 { b.Write(crnl) if err := p.encodeContent(b, cte); err != nil { return err } } if p.FirstChild == nil { return b.Flush() } // Encode children. endMarker := []byte("\r\n--" + p.Boundary + "--") marker := endMarker[:len(endMarker)-2] c := p.FirstChild for c != nil { b.Write(marker) b.Write(crnl) if err := c.Encode(b); err != nil { return err } c = c.NextSibling } b.Write(endMarker) b.Write(crnl) return b.Flush() }
[ "func", "(", "p", "*", "Part", ")", "Encode", "(", "writer", "io", ".", "Writer", ")", "error", "{", "if", "p", ".", "Header", "==", "nil", "{", "p", ".", "Header", "=", "make", "(", "textproto", ".", "MIMEHeader", ")", "\n", "}", "\n", "cte", ":=", "p", ".", "setupMIMEHeaders", "(", ")", "\n", "b", ":=", "bufio", ".", "NewWriter", "(", "writer", ")", "\n", "p", ".", "encodeHeader", "(", "b", ")", "\n", "if", "len", "(", "p", ".", "Content", ")", ">", "0", "{", "b", ".", "Write", "(", "crnl", ")", "\n", "if", "err", ":=", "p", ".", "encodeContent", "(", "b", ",", "cte", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "p", ".", "FirstChild", "==", "nil", "{", "return", "b", ".", "Flush", "(", ")", "\n", "}", "\n", "endMarker", ":=", "[", "]", "byte", "(", "\"\\r\\n--\"", "+", "\\r", "+", "\\n", ")", "\n", "p", ".", "Boundary", "\n", "\"--\"", "\n", "marker", ":=", "endMarker", "[", ":", "len", "(", "endMarker", ")", "-", "2", "]", "\n", "c", ":=", "p", ".", "FirstChild", "\n", "for", "c", "!=", "nil", "{", "b", ".", "Write", "(", "marker", ")", "\n", "b", ".", "Write", "(", "crnl", ")", "\n", "if", "err", ":=", "c", ".", "Encode", "(", "b", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", "=", "c", ".", "NextSibling", "\n", "}", "\n", "b", ".", "Write", "(", "endMarker", ")", "\n", "}" ]
// Encode writes this Part and all its children to the specified writer in MIME format.
[ "Encode", "writes", "this", "Part", "and", "all", "its", "children", "to", "the", "specified", "writer", "in", "MIME", "format", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/encode.go#L32-L64
test
jhillyerd/enmime
encode.go
encodeHeader
func (p *Part) encodeHeader(b *bufio.Writer) { keys := make([]string, 0, len(p.Header)) for k := range p.Header { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { for _, v := range p.Header[k] { encv := v switch selectTransferEncoding([]byte(v), true) { case teBase64: encv = mime.BEncoding.Encode(utf8, v) case teQuoted: encv = mime.QEncoding.Encode(utf8, v) } // _ used to prevent early wrapping wb := stringutil.Wrap(76, k, ":_", encv, "\r\n") wb[len(k)+1] = ' ' b.Write(wb) } } }
go
func (p *Part) encodeHeader(b *bufio.Writer) { keys := make([]string, 0, len(p.Header)) for k := range p.Header { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { for _, v := range p.Header[k] { encv := v switch selectTransferEncoding([]byte(v), true) { case teBase64: encv = mime.BEncoding.Encode(utf8, v) case teQuoted: encv = mime.QEncoding.Encode(utf8, v) } // _ used to prevent early wrapping wb := stringutil.Wrap(76, k, ":_", encv, "\r\n") wb[len(k)+1] = ' ' b.Write(wb) } } }
[ "func", "(", "p", "*", "Part", ")", "encodeHeader", "(", "b", "*", "bufio", ".", "Writer", ")", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "p", ".", "Header", ")", ")", "\n", "for", "k", ":=", "range", "p", ".", "Header", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "for", "_", ",", "v", ":=", "range", "p", ".", "Header", "[", "k", "]", "{", "encv", ":=", "v", "\n", "switch", "selectTransferEncoding", "(", "[", "]", "byte", "(", "v", ")", ",", "true", ")", "{", "case", "teBase64", ":", "encv", "=", "mime", ".", "BEncoding", ".", "Encode", "(", "utf8", ",", "v", ")", "\n", "case", "teQuoted", ":", "encv", "=", "mime", ".", "QEncoding", ".", "Encode", "(", "utf8", ",", "v", ")", "\n", "}", "\n", "wb", ":=", "stringutil", ".", "Wrap", "(", "76", ",", "k", ",", "\":_\"", ",", "encv", ",", "\"\\r\\n\"", ")", "\n", "\\r", "\n", "\\n", "\n", "}", "\n", "}", "\n", "}" ]
// encodeHeader writes out a sorted list of headers.
[ "encodeHeader", "writes", "out", "a", "sorted", "list", "of", "headers", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/encode.go#L131-L152
test
jhillyerd/enmime
encode.go
encodeContent
func (p *Part) encodeContent(b *bufio.Writer, cte transferEncoding) (err error) { switch cte { case teBase64: enc := base64.StdEncoding text := make([]byte, enc.EncodedLen(len(p.Content))) base64.StdEncoding.Encode(text, p.Content) // Wrap lines. lineLen := 76 for len(text) > 0 { if lineLen > len(text) { lineLen = len(text) } if _, err = b.Write(text[:lineLen]); err != nil { return err } b.Write(crnl) text = text[lineLen:] } case teQuoted: qp := quotedprintable.NewWriter(b) if _, err = qp.Write(p.Content); err != nil { return err } err = qp.Close() default: _, err = b.Write(p.Content) } return err }
go
func (p *Part) encodeContent(b *bufio.Writer, cte transferEncoding) (err error) { switch cte { case teBase64: enc := base64.StdEncoding text := make([]byte, enc.EncodedLen(len(p.Content))) base64.StdEncoding.Encode(text, p.Content) // Wrap lines. lineLen := 76 for len(text) > 0 { if lineLen > len(text) { lineLen = len(text) } if _, err = b.Write(text[:lineLen]); err != nil { return err } b.Write(crnl) text = text[lineLen:] } case teQuoted: qp := quotedprintable.NewWriter(b) if _, err = qp.Write(p.Content); err != nil { return err } err = qp.Close() default: _, err = b.Write(p.Content) } return err }
[ "func", "(", "p", "*", "Part", ")", "encodeContent", "(", "b", "*", "bufio", ".", "Writer", ",", "cte", "transferEncoding", ")", "(", "err", "error", ")", "{", "switch", "cte", "{", "case", "teBase64", ":", "enc", ":=", "base64", ".", "StdEncoding", "\n", "text", ":=", "make", "(", "[", "]", "byte", ",", "enc", ".", "EncodedLen", "(", "len", "(", "p", ".", "Content", ")", ")", ")", "\n", "base64", ".", "StdEncoding", ".", "Encode", "(", "text", ",", "p", ".", "Content", ")", "\n", "lineLen", ":=", "76", "\n", "for", "len", "(", "text", ")", ">", "0", "{", "if", "lineLen", ">", "len", "(", "text", ")", "{", "lineLen", "=", "len", "(", "text", ")", "\n", "}", "\n", "if", "_", ",", "err", "=", "b", ".", "Write", "(", "text", "[", ":", "lineLen", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "b", ".", "Write", "(", "crnl", ")", "\n", "text", "=", "text", "[", "lineLen", ":", "]", "\n", "}", "\n", "case", "teQuoted", ":", "qp", ":=", "quotedprintable", ".", "NewWriter", "(", "b", ")", "\n", "if", "_", ",", "err", "=", "qp", ".", "Write", "(", "p", ".", "Content", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "qp", ".", "Close", "(", ")", "\n", "default", ":", "_", ",", "err", "=", "b", ".", "Write", "(", "p", ".", "Content", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// encodeContent writes out the content in the selected encoding.
[ "encodeContent", "writes", "out", "the", "content", "in", "the", "selected", "encoding", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/encode.go#L155-L183
test
jhillyerd/enmime
encode.go
selectTransferEncoding
func selectTransferEncoding(content []byte, quoteLineBreaks bool) transferEncoding { if len(content) == 0 { return te7Bit } // Binary chars remaining before we choose b64 encoding. threshold := b64Percent * len(content) / 100 bincount := 0 for _, b := range content { if (b < ' ' || '~' < b) && b != '\t' { if !quoteLineBreaks && (b == '\r' || b == '\n') { continue } bincount++ if bincount >= threshold { return teBase64 } } } if bincount == 0 { return te7Bit } return teQuoted }
go
func selectTransferEncoding(content []byte, quoteLineBreaks bool) transferEncoding { if len(content) == 0 { return te7Bit } // Binary chars remaining before we choose b64 encoding. threshold := b64Percent * len(content) / 100 bincount := 0 for _, b := range content { if (b < ' ' || '~' < b) && b != '\t' { if !quoteLineBreaks && (b == '\r' || b == '\n') { continue } bincount++ if bincount >= threshold { return teBase64 } } } if bincount == 0 { return te7Bit } return teQuoted }
[ "func", "selectTransferEncoding", "(", "content", "[", "]", "byte", ",", "quoteLineBreaks", "bool", ")", "transferEncoding", "{", "if", "len", "(", "content", ")", "==", "0", "{", "return", "te7Bit", "\n", "}", "\n", "threshold", ":=", "b64Percent", "*", "len", "(", "content", ")", "/", "100", "\n", "bincount", ":=", "0", "\n", "for", "_", ",", "b", ":=", "range", "content", "{", "if", "(", "b", "<", "' '", "||", "'~'", "<", "b", ")", "&&", "b", "!=", "'\\t'", "{", "if", "!", "quoteLineBreaks", "&&", "(", "b", "==", "'\\r'", "||", "b", "==", "'\\n'", ")", "{", "continue", "\n", "}", "\n", "bincount", "++", "\n", "if", "bincount", ">=", "threshold", "{", "return", "teBase64", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "bincount", "==", "0", "{", "return", "te7Bit", "\n", "}", "\n", "return", "teQuoted", "\n", "}" ]
// selectTransferEncoding scans content for non-ASCII characters and selects 'b' or 'q' encoding.
[ "selectTransferEncoding", "scans", "content", "for", "non", "-", "ASCII", "characters", "and", "selects", "b", "or", "q", "encoding", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/encode.go#L186-L208
test
jhillyerd/enmime
encode.go
setParamValue
func setParamValue(p map[string]string, k, v string) { if v != "" { p[k] = v } }
go
func setParamValue(p map[string]string, k, v string) { if v != "" { p[k] = v } }
[ "func", "setParamValue", "(", "p", "map", "[", "string", "]", "string", ",", "k", ",", "v", "string", ")", "{", "if", "v", "!=", "\"\"", "{", "p", "[", "k", "]", "=", "v", "\n", "}", "\n", "}" ]
// setParamValue will ignore empty values
[ "setParamValue", "will", "ignore", "empty", "values" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/encode.go#L211-L215
test
jhillyerd/enmime
internal/coding/base64.go
NewBase64Cleaner
func NewBase64Cleaner(r io.Reader) *Base64Cleaner { return &Base64Cleaner{ Errors: make([]error, 0), r: r, } }
go
func NewBase64Cleaner(r io.Reader) *Base64Cleaner { return &Base64Cleaner{ Errors: make([]error, 0), r: r, } }
[ "func", "NewBase64Cleaner", "(", "r", "io", ".", "Reader", ")", "*", "Base64Cleaner", "{", "return", "&", "Base64Cleaner", "{", "Errors", ":", "make", "(", "[", "]", "error", ",", "0", ")", ",", "r", ":", "r", ",", "}", "\n", "}" ]
// NewBase64Cleaner returns a Base64Cleaner object for the specified reader. Base64Cleaner // implements the io.Reader interface.
[ "NewBase64Cleaner", "returns", "a", "Base64Cleaner", "object", "for", "the", "specified", "reader", ".", "Base64Cleaner", "implements", "the", "io", ".", "Reader", "interface", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/coding/base64.go#L35-L40
test
jhillyerd/enmime
header.go
decodeToUTF8Base64Header
func decodeToUTF8Base64Header(input string) string { if !strings.Contains(input, "=?") { // Don't scan if there is nothing to do here return input } tokens := strings.FieldsFunc(input, whiteSpaceRune) output := make([]string, len(tokens)) for i, token := range tokens { if len(token) > 4 && strings.Contains(token, "=?") { // Stash parenthesis, they should not be encoded prefix := "" suffix := "" if token[0] == '(' { prefix = "(" token = token[1:] } if token[len(token)-1] == ')' { suffix = ")" token = token[:len(token)-1] } // Base64 encode token output[i] = prefix + mime.BEncoding.Encode("UTF-8", decodeHeader(token)) + suffix } else { output[i] = token } } // Return space separated tokens return strings.Join(output, " ") }
go
func decodeToUTF8Base64Header(input string) string { if !strings.Contains(input, "=?") { // Don't scan if there is nothing to do here return input } tokens := strings.FieldsFunc(input, whiteSpaceRune) output := make([]string, len(tokens)) for i, token := range tokens { if len(token) > 4 && strings.Contains(token, "=?") { // Stash parenthesis, they should not be encoded prefix := "" suffix := "" if token[0] == '(' { prefix = "(" token = token[1:] } if token[len(token)-1] == ')' { suffix = ")" token = token[:len(token)-1] } // Base64 encode token output[i] = prefix + mime.BEncoding.Encode("UTF-8", decodeHeader(token)) + suffix } else { output[i] = token } } // Return space separated tokens return strings.Join(output, " ") }
[ "func", "decodeToUTF8Base64Header", "(", "input", "string", ")", "string", "{", "if", "!", "strings", ".", "Contains", "(", "input", ",", "\"=?\"", ")", "{", "return", "input", "\n", "}", "\n", "tokens", ":=", "strings", ".", "FieldsFunc", "(", "input", ",", "whiteSpaceRune", ")", "\n", "output", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "tokens", ")", ")", "\n", "for", "i", ",", "token", ":=", "range", "tokens", "{", "if", "len", "(", "token", ")", ">", "4", "&&", "strings", ".", "Contains", "(", "token", ",", "\"=?\"", ")", "{", "prefix", ":=", "\"\"", "\n", "suffix", ":=", "\"\"", "\n", "if", "token", "[", "0", "]", "==", "'('", "{", "prefix", "=", "\"(\"", "\n", "token", "=", "token", "[", "1", ":", "]", "\n", "}", "\n", "if", "token", "[", "len", "(", "token", ")", "-", "1", "]", "==", "')'", "{", "suffix", "=", "\")\"", "\n", "token", "=", "token", "[", ":", "len", "(", "token", ")", "-", "1", "]", "\n", "}", "\n", "output", "[", "i", "]", "=", "prefix", "+", "mime", ".", "BEncoding", ".", "Encode", "(", "\"UTF-8\"", ",", "decodeHeader", "(", "token", ")", ")", "+", "suffix", "\n", "}", "else", "{", "output", "[", "i", "]", "=", "token", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "output", ",", "\" \"", ")", "\n", "}" ]
// decodeToUTF8Base64Header decodes a MIME header per RFC 2047, reencoding to =?utf-8b?
[ "decodeToUTF8Base64Header", "decodes", "a", "MIME", "header", "per", "RFC", "2047", "reencoding", "to", "=", "?utf", "-", "8b?" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L167-L197
test
jhillyerd/enmime
header.go
parseMediaType
func parseMediaType(ctype string) (mtype string, params map[string]string, invalidParams []string, err error) { mtype, params, err = mime.ParseMediaType(ctype) if err != nil { // Small hack to remove harmless charset duplicate params. mctype := fixMangledMediaType(ctype, ";") mtype, params, err = mime.ParseMediaType(mctype) if err != nil { // Some badly formed media types forget to send ; between fields. mctype := fixMangledMediaType(ctype, " ") if strings.Contains(mctype, `name=""`) { mctype = strings.Replace(mctype, `name=""`, `name=" "`, -1) } mtype, params, err = mime.ParseMediaType(mctype) if err != nil { // If the media parameter has special characters, ensure that it is quoted. mtype, params, err = mime.ParseMediaType(fixUnquotedSpecials(mctype)) if err != nil { return "", nil, nil, errors.WithStack(err) } } } } if mtype == ctPlaceholder { mtype = "" } for name, value := range params { if value != pvPlaceholder { continue } invalidParams = append(invalidParams, name) delete(params, name) } return mtype, params, invalidParams, err }
go
func parseMediaType(ctype string) (mtype string, params map[string]string, invalidParams []string, err error) { mtype, params, err = mime.ParseMediaType(ctype) if err != nil { // Small hack to remove harmless charset duplicate params. mctype := fixMangledMediaType(ctype, ";") mtype, params, err = mime.ParseMediaType(mctype) if err != nil { // Some badly formed media types forget to send ; between fields. mctype := fixMangledMediaType(ctype, " ") if strings.Contains(mctype, `name=""`) { mctype = strings.Replace(mctype, `name=""`, `name=" "`, -1) } mtype, params, err = mime.ParseMediaType(mctype) if err != nil { // If the media parameter has special characters, ensure that it is quoted. mtype, params, err = mime.ParseMediaType(fixUnquotedSpecials(mctype)) if err != nil { return "", nil, nil, errors.WithStack(err) } } } } if mtype == ctPlaceholder { mtype = "" } for name, value := range params { if value != pvPlaceholder { continue } invalidParams = append(invalidParams, name) delete(params, name) } return mtype, params, invalidParams, err }
[ "func", "parseMediaType", "(", "ctype", "string", ")", "(", "mtype", "string", ",", "params", "map", "[", "string", "]", "string", ",", "invalidParams", "[", "]", "string", ",", "err", "error", ")", "{", "mtype", ",", "params", ",", "err", "=", "mime", ".", "ParseMediaType", "(", "ctype", ")", "\n", "if", "err", "!=", "nil", "{", "mctype", ":=", "fixMangledMediaType", "(", "ctype", ",", "\";\"", ")", "\n", "mtype", ",", "params", ",", "err", "=", "mime", ".", "ParseMediaType", "(", "mctype", ")", "\n", "if", "err", "!=", "nil", "{", "mctype", ":=", "fixMangledMediaType", "(", "ctype", ",", "\" \"", ")", "\n", "if", "strings", ".", "Contains", "(", "mctype", ",", "`name=\"\"`", ")", "{", "mctype", "=", "strings", ".", "Replace", "(", "mctype", ",", "`name=\"\"`", ",", "`name=\" \"`", ",", "-", "1", ")", "\n", "}", "\n", "mtype", ",", "params", ",", "err", "=", "mime", ".", "ParseMediaType", "(", "mctype", ")", "\n", "if", "err", "!=", "nil", "{", "mtype", ",", "params", ",", "err", "=", "mime", ".", "ParseMediaType", "(", "fixUnquotedSpecials", "(", "mctype", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "nil", ",", "nil", ",", "errors", ".", "WithStack", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "mtype", "==", "ctPlaceholder", "{", "mtype", "=", "\"\"", "\n", "}", "\n", "for", "name", ",", "value", ":=", "range", "params", "{", "if", "value", "!=", "pvPlaceholder", "{", "continue", "\n", "}", "\n", "invalidParams", "=", "append", "(", "invalidParams", ",", "name", ")", "\n", "delete", "(", "params", ",", "name", ")", "\n", "}", "\n", "return", "mtype", ",", "params", ",", "invalidParams", ",", "err", "\n", "}" ]
// parseMediaType is a more tolerant implementation of Go's mime.ParseMediaType function.
[ "parseMediaType", "is", "a", "more", "tolerant", "implementation", "of", "Go", "s", "mime", ".", "ParseMediaType", "function", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L200-L233
test
jhillyerd/enmime
header.go
fixMangledMediaType
func fixMangledMediaType(mtype, sep string) string { if mtype == "" { return "" } parts := strings.Split(mtype, sep) mtype = "" for i, p := range parts { switch i { case 0: if p == "" { // The content type is completely missing. Put in a placeholder. p = ctPlaceholder } default: if !strings.Contains(p, "=") { p = p + "=" + pvPlaceholder } // RFC-2047 encoded attribute name p = rfc2047AttributeName(p) pair := strings.Split(p, "=") if strings.Contains(mtype, pair[0]+"=") { // Ignore repeated parameters. continue } if strings.ContainsAny(pair[0], "()<>@,;:\"\\/[]?") { // attribute is a strict token and cannot be a quoted-string // if any of the above characters are present in a token it // must be quoted and is therefor an invalid attribute. // Discard the pair. continue } } mtype += p // Only terminate with semicolon if not the last parameter and if it doesn't already have a // semicolon. if i != len(parts)-1 && !strings.HasSuffix(mtype, ";") { mtype += ";" } } if strings.HasSuffix(mtype, ";") { mtype = mtype[:len(mtype)-1] } return mtype }
go
func fixMangledMediaType(mtype, sep string) string { if mtype == "" { return "" } parts := strings.Split(mtype, sep) mtype = "" for i, p := range parts { switch i { case 0: if p == "" { // The content type is completely missing. Put in a placeholder. p = ctPlaceholder } default: if !strings.Contains(p, "=") { p = p + "=" + pvPlaceholder } // RFC-2047 encoded attribute name p = rfc2047AttributeName(p) pair := strings.Split(p, "=") if strings.Contains(mtype, pair[0]+"=") { // Ignore repeated parameters. continue } if strings.ContainsAny(pair[0], "()<>@,;:\"\\/[]?") { // attribute is a strict token and cannot be a quoted-string // if any of the above characters are present in a token it // must be quoted and is therefor an invalid attribute. // Discard the pair. continue } } mtype += p // Only terminate with semicolon if not the last parameter and if it doesn't already have a // semicolon. if i != len(parts)-1 && !strings.HasSuffix(mtype, ";") { mtype += ";" } } if strings.HasSuffix(mtype, ";") { mtype = mtype[:len(mtype)-1] } return mtype }
[ "func", "fixMangledMediaType", "(", "mtype", ",", "sep", "string", ")", "string", "{", "if", "mtype", "==", "\"\"", "{", "return", "\"\"", "\n", "}", "\n", "parts", ":=", "strings", ".", "Split", "(", "mtype", ",", "sep", ")", "\n", "mtype", "=", "\"\"", "\n", "for", "i", ",", "p", ":=", "range", "parts", "{", "switch", "i", "{", "case", "0", ":", "if", "p", "==", "\"\"", "{", "p", "=", "ctPlaceholder", "\n", "}", "\n", "default", ":", "if", "!", "strings", ".", "Contains", "(", "p", ",", "\"=\"", ")", "{", "p", "=", "p", "+", "\"=\"", "+", "pvPlaceholder", "\n", "}", "\n", "p", "=", "rfc2047AttributeName", "(", "p", ")", "\n", "pair", ":=", "strings", ".", "Split", "(", "p", ",", "\"=\"", ")", "\n", "if", "strings", ".", "Contains", "(", "mtype", ",", "pair", "[", "0", "]", "+", "\"=\"", ")", "{", "continue", "\n", "}", "\n", "if", "strings", ".", "ContainsAny", "(", "pair", "[", "0", "]", ",", "\"()<>@,;:\\\"\\\\/[]?\"", ")", "\\\"", "\n", "}", "\n", "\\\\", "\n", "{", "continue", "\n", "}", "\n", "}", "\n", "mtype", "+=", "p", "\n", "if", "i", "!=", "len", "(", "parts", ")", "-", "1", "&&", "!", "strings", ".", "HasSuffix", "(", "mtype", ",", "\";\"", ")", "{", "mtype", "+=", "\";\"", "\n", "}", "\n", "}" ]
// fixMangledMediaType is used to insert ; separators into media type strings that lack them, and // remove repeated parameters.
[ "fixMangledMediaType", "is", "used", "to", "insert", ";", "separators", "into", "media", "type", "strings", "that", "lack", "them", "and", "remove", "repeated", "parameters", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L237-L283
test
jhillyerd/enmime
detect.go
detectMultipartMessage
func detectMultipartMessage(root *Part) bool { // Parse top-level multipart ctype := root.Header.Get(hnContentType) mediatype, _, _, err := parseMediaType(ctype) if err != nil { return false } // According to rfc2046#section-5.1.7 all other multipart should // be treated as multipart/mixed return strings.HasPrefix(mediatype, ctMultipartPrefix) }
go
func detectMultipartMessage(root *Part) bool { // Parse top-level multipart ctype := root.Header.Get(hnContentType) mediatype, _, _, err := parseMediaType(ctype) if err != nil { return false } // According to rfc2046#section-5.1.7 all other multipart should // be treated as multipart/mixed return strings.HasPrefix(mediatype, ctMultipartPrefix) }
[ "func", "detectMultipartMessage", "(", "root", "*", "Part", ")", "bool", "{", "ctype", ":=", "root", ".", "Header", ".", "Get", "(", "hnContentType", ")", "\n", "mediatype", ",", "_", ",", "_", ",", "err", ":=", "parseMediaType", "(", "ctype", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "strings", ".", "HasPrefix", "(", "mediatype", ",", "ctMultipartPrefix", ")", "\n", "}" ]
// detectMultipartMessage returns true if the message has a recognized multipart Content-Type header
[ "detectMultipartMessage", "returns", "true", "if", "the", "message", "has", "a", "recognized", "multipart", "Content", "-", "Type", "header" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/detect.go#L9-L19
test
jhillyerd/enmime
detect.go
detectBinaryBody
func detectBinaryBody(root *Part) bool { if detectTextHeader(root.Header, true) { return false } isBin := detectAttachmentHeader(root.Header) if !isBin { // This must be an attachment, if the Content-Type is not // 'text/plain' or 'text/html'. // Example: // Content-Type: application/pdf; name="doc.pdf" mediatype, _, _, _ := parseMediaType(root.Header.Get(hnContentType)) mediatype = strings.ToLower(mediatype) if mediatype != ctTextPlain && mediatype != ctTextHTML { return true } } return isBin }
go
func detectBinaryBody(root *Part) bool { if detectTextHeader(root.Header, true) { return false } isBin := detectAttachmentHeader(root.Header) if !isBin { // This must be an attachment, if the Content-Type is not // 'text/plain' or 'text/html'. // Example: // Content-Type: application/pdf; name="doc.pdf" mediatype, _, _, _ := parseMediaType(root.Header.Get(hnContentType)) mediatype = strings.ToLower(mediatype) if mediatype != ctTextPlain && mediatype != ctTextHTML { return true } } return isBin }
[ "func", "detectBinaryBody", "(", "root", "*", "Part", ")", "bool", "{", "if", "detectTextHeader", "(", "root", ".", "Header", ",", "true", ")", "{", "return", "false", "\n", "}", "\n", "isBin", ":=", "detectAttachmentHeader", "(", "root", ".", "Header", ")", "\n", "if", "!", "isBin", "{", "mediatype", ",", "_", ",", "_", ",", "_", ":=", "parseMediaType", "(", "root", ".", "Header", ".", "Get", "(", "hnContentType", ")", ")", "\n", "mediatype", "=", "strings", ".", "ToLower", "(", "mediatype", ")", "\n", "if", "mediatype", "!=", "ctTextPlain", "&&", "mediatype", "!=", "ctTextHTML", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "isBin", "\n", "}" ]
// detectBinaryBody returns true if the mail header defines a binary body.
[ "detectBinaryBody", "returns", "true", "if", "the", "mail", "header", "defines", "a", "binary", "body", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/detect.go#L64-L83
test
jhillyerd/enmime
match.go
BreadthMatchFirst
func (p *Part) BreadthMatchFirst(matcher PartMatcher) *Part { q := list.New() q.PushBack(p) // Push children onto queue and attempt to match in that order for q.Len() > 0 { e := q.Front() p := e.Value.(*Part) if matcher(p) { return p } q.Remove(e) c := p.FirstChild for c != nil { q.PushBack(c) c = c.NextSibling } } return nil }
go
func (p *Part) BreadthMatchFirst(matcher PartMatcher) *Part { q := list.New() q.PushBack(p) // Push children onto queue and attempt to match in that order for q.Len() > 0 { e := q.Front() p := e.Value.(*Part) if matcher(p) { return p } q.Remove(e) c := p.FirstChild for c != nil { q.PushBack(c) c = c.NextSibling } } return nil }
[ "func", "(", "p", "*", "Part", ")", "BreadthMatchFirst", "(", "matcher", "PartMatcher", ")", "*", "Part", "{", "q", ":=", "list", ".", "New", "(", ")", "\n", "q", ".", "PushBack", "(", "p", ")", "\n", "for", "q", ".", "Len", "(", ")", ">", "0", "{", "e", ":=", "q", ".", "Front", "(", ")", "\n", "p", ":=", "e", ".", "Value", ".", "(", "*", "Part", ")", "\n", "if", "matcher", "(", "p", ")", "{", "return", "p", "\n", "}", "\n", "q", ".", "Remove", "(", "e", ")", "\n", "c", ":=", "p", ".", "FirstChild", "\n", "for", "c", "!=", "nil", "{", "q", ".", "PushBack", "(", "c", ")", "\n", "c", "=", "c", ".", "NextSibling", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// BreadthMatchFirst performs a breadth first search of the Part tree and returns the first part // that causes the given matcher to return true
[ "BreadthMatchFirst", "performs", "a", "breadth", "first", "search", "of", "the", "Part", "tree", "and", "returns", "the", "first", "part", "that", "causes", "the", "given", "matcher", "to", "return", "true" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/match.go#L14-L34
test
jhillyerd/enmime
match.go
BreadthMatchAll
func (p *Part) BreadthMatchAll(matcher PartMatcher) []*Part { q := list.New() q.PushBack(p) matches := make([]*Part, 0, 10) // Push children onto queue and attempt to match in that order for q.Len() > 0 { e := q.Front() p := e.Value.(*Part) if matcher(p) { matches = append(matches, p) } q.Remove(e) c := p.FirstChild for c != nil { q.PushBack(c) c = c.NextSibling } } return matches }
go
func (p *Part) BreadthMatchAll(matcher PartMatcher) []*Part { q := list.New() q.PushBack(p) matches := make([]*Part, 0, 10) // Push children onto queue and attempt to match in that order for q.Len() > 0 { e := q.Front() p := e.Value.(*Part) if matcher(p) { matches = append(matches, p) } q.Remove(e) c := p.FirstChild for c != nil { q.PushBack(c) c = c.NextSibling } } return matches }
[ "func", "(", "p", "*", "Part", ")", "BreadthMatchAll", "(", "matcher", "PartMatcher", ")", "[", "]", "*", "Part", "{", "q", ":=", "list", ".", "New", "(", ")", "\n", "q", ".", "PushBack", "(", "p", ")", "\n", "matches", ":=", "make", "(", "[", "]", "*", "Part", ",", "0", ",", "10", ")", "\n", "for", "q", ".", "Len", "(", ")", ">", "0", "{", "e", ":=", "q", ".", "Front", "(", ")", "\n", "p", ":=", "e", ".", "Value", ".", "(", "*", "Part", ")", "\n", "if", "matcher", "(", "p", ")", "{", "matches", "=", "append", "(", "matches", ",", "p", ")", "\n", "}", "\n", "q", ".", "Remove", "(", "e", ")", "\n", "c", ":=", "p", ".", "FirstChild", "\n", "for", "c", "!=", "nil", "{", "q", ".", "PushBack", "(", "c", ")", "\n", "c", "=", "c", ".", "NextSibling", "\n", "}", "\n", "}", "\n", "return", "matches", "\n", "}" ]
// BreadthMatchAll performs a breadth first search of the Part tree and returns all parts that cause // the given matcher to return true
[ "BreadthMatchAll", "performs", "a", "breadth", "first", "search", "of", "the", "Part", "tree", "and", "returns", "all", "parts", "that", "cause", "the", "given", "matcher", "to", "return", "true" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/match.go#L38-L60
test
jhillyerd/enmime
match.go
DepthMatchFirst
func (p *Part) DepthMatchFirst(matcher PartMatcher) *Part { root := p for { if matcher(p) { return p } c := p.FirstChild if c != nil { p = c } else { for p.NextSibling == nil { if p == root { return nil } p = p.Parent } p = p.NextSibling } } }
go
func (p *Part) DepthMatchFirst(matcher PartMatcher) *Part { root := p for { if matcher(p) { return p } c := p.FirstChild if c != nil { p = c } else { for p.NextSibling == nil { if p == root { return nil } p = p.Parent } p = p.NextSibling } } }
[ "func", "(", "p", "*", "Part", ")", "DepthMatchFirst", "(", "matcher", "PartMatcher", ")", "*", "Part", "{", "root", ":=", "p", "\n", "for", "{", "if", "matcher", "(", "p", ")", "{", "return", "p", "\n", "}", "\n", "c", ":=", "p", ".", "FirstChild", "\n", "if", "c", "!=", "nil", "{", "p", "=", "c", "\n", "}", "else", "{", "for", "p", ".", "NextSibling", "==", "nil", "{", "if", "p", "==", "root", "{", "return", "nil", "\n", "}", "\n", "p", "=", "p", ".", "Parent", "\n", "}", "\n", "p", "=", "p", ".", "NextSibling", "\n", "}", "\n", "}", "\n", "}" ]
// DepthMatchFirst performs a depth first search of the Part tree and returns the first part that // causes the given matcher to return true
[ "DepthMatchFirst", "performs", "a", "depth", "first", "search", "of", "the", "Part", "tree", "and", "returns", "the", "first", "part", "that", "causes", "the", "given", "matcher", "to", "return", "true" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/match.go#L64-L83
test
jhillyerd/enmime
match.go
DepthMatchAll
func (p *Part) DepthMatchAll(matcher PartMatcher) []*Part { root := p matches := make([]*Part, 0, 10) for { if matcher(p) { matches = append(matches, p) } c := p.FirstChild if c != nil { p = c } else { for p.NextSibling == nil { if p == root { return matches } p = p.Parent } p = p.NextSibling } } }
go
func (p *Part) DepthMatchAll(matcher PartMatcher) []*Part { root := p matches := make([]*Part, 0, 10) for { if matcher(p) { matches = append(matches, p) } c := p.FirstChild if c != nil { p = c } else { for p.NextSibling == nil { if p == root { return matches } p = p.Parent } p = p.NextSibling } } }
[ "func", "(", "p", "*", "Part", ")", "DepthMatchAll", "(", "matcher", "PartMatcher", ")", "[", "]", "*", "Part", "{", "root", ":=", "p", "\n", "matches", ":=", "make", "(", "[", "]", "*", "Part", ",", "0", ",", "10", ")", "\n", "for", "{", "if", "matcher", "(", "p", ")", "{", "matches", "=", "append", "(", "matches", ",", "p", ")", "\n", "}", "\n", "c", ":=", "p", ".", "FirstChild", "\n", "if", "c", "!=", "nil", "{", "p", "=", "c", "\n", "}", "else", "{", "for", "p", ".", "NextSibling", "==", "nil", "{", "if", "p", "==", "root", "{", "return", "matches", "\n", "}", "\n", "p", "=", "p", ".", "Parent", "\n", "}", "\n", "p", "=", "p", ".", "NextSibling", "\n", "}", "\n", "}", "\n", "}" ]
// DepthMatchAll performs a depth first search of the Part tree and returns all parts that causes // the given matcher to return true
[ "DepthMatchAll", "performs", "a", "depth", "first", "search", "of", "the", "Part", "tree", "and", "returns", "all", "parts", "that", "causes", "the", "given", "matcher", "to", "return", "true" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/match.go#L87-L107
test
jhillyerd/enmime
internal/stringutil/unicode.go
ToASCII
func ToASCII(s string) string { // unicode.Mn: nonspacing marks tr := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), runes.Map(mapLatinSpecial), norm.NFC) r, _, _ := transform.String(tr, s) return r }
go
func ToASCII(s string) string { // unicode.Mn: nonspacing marks tr := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), runes.Map(mapLatinSpecial), norm.NFC) r, _, _ := transform.String(tr, s) return r }
[ "func", "ToASCII", "(", "s", "string", ")", "string", "{", "tr", ":=", "transform", ".", "Chain", "(", "norm", ".", "NFD", ",", "runes", ".", "Remove", "(", "runes", ".", "In", "(", "unicode", ".", "Mn", ")", ")", ",", "runes", ".", "Map", "(", "mapLatinSpecial", ")", ",", "norm", ".", "NFC", ")", "\n", "r", ",", "_", ",", "_", ":=", "transform", ".", "String", "(", "tr", ",", "s", ")", "\n", "return", "r", "\n", "}" ]
// ToASCII converts unicode to ASCII by stripping accents and converting some special characters // into their ASCII approximations. Anything else will be replaced with an underscore.
[ "ToASCII", "converts", "unicode", "to", "ASCII", "by", "stripping", "accents", "and", "converting", "some", "special", "characters", "into", "their", "ASCII", "approximations", ".", "Anything", "else", "will", "be", "replaced", "with", "an", "underscore", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/stringutil/unicode.go#L47-L53
test
jhillyerd/enmime
part.go
NewPart
func NewPart(contentType string) *Part { return &Part{ Header: make(textproto.MIMEHeader), ContentType: contentType, } }
go
func NewPart(contentType string) *Part { return &Part{ Header: make(textproto.MIMEHeader), ContentType: contentType, } }
[ "func", "NewPart", "(", "contentType", "string", ")", "*", "Part", "{", "return", "&", "Part", "{", "Header", ":", "make", "(", "textproto", ".", "MIMEHeader", ")", ",", "ContentType", ":", "contentType", ",", "}", "\n", "}" ]
// NewPart creates a new Part object.
[ "NewPart", "creates", "a", "new", "Part", "object", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L47-L52
test
jhillyerd/enmime
part.go
AddChild
func (p *Part) AddChild(child *Part) { if p == child { // Prevent paradox. return } if p != nil { if p.FirstChild == nil { // Make it the first child. p.FirstChild = child } else { // Append to sibling chain. current := p.FirstChild for current.NextSibling != nil { current = current.NextSibling } if current == child { // Prevent infinite loop. return } current.NextSibling = child } } // Update all new first-level children Parent pointers. for c := child; c != nil; c = c.NextSibling { if c == c.NextSibling { // Prevent infinite loop. return } c.Parent = p } }
go
func (p *Part) AddChild(child *Part) { if p == child { // Prevent paradox. return } if p != nil { if p.FirstChild == nil { // Make it the first child. p.FirstChild = child } else { // Append to sibling chain. current := p.FirstChild for current.NextSibling != nil { current = current.NextSibling } if current == child { // Prevent infinite loop. return } current.NextSibling = child } } // Update all new first-level children Parent pointers. for c := child; c != nil; c = c.NextSibling { if c == c.NextSibling { // Prevent infinite loop. return } c.Parent = p } }
[ "func", "(", "p", "*", "Part", ")", "AddChild", "(", "child", "*", "Part", ")", "{", "if", "p", "==", "child", "{", "return", "\n", "}", "\n", "if", "p", "!=", "nil", "{", "if", "p", ".", "FirstChild", "==", "nil", "{", "p", ".", "FirstChild", "=", "child", "\n", "}", "else", "{", "current", ":=", "p", ".", "FirstChild", "\n", "for", "current", ".", "NextSibling", "!=", "nil", "{", "current", "=", "current", ".", "NextSibling", "\n", "}", "\n", "if", "current", "==", "child", "{", "return", "\n", "}", "\n", "current", ".", "NextSibling", "=", "child", "\n", "}", "\n", "}", "\n", "for", "c", ":=", "child", ";", "c", "!=", "nil", ";", "c", "=", "c", ".", "NextSibling", "{", "if", "c", "==", "c", ".", "NextSibling", "{", "return", "\n", "}", "\n", "c", ".", "Parent", "=", "p", "\n", "}", "\n", "}" ]
// AddChild adds a child part to either FirstChild or the end of the children NextSibling chain. // The child may have siblings and children attached. This method will set the Parent field on // child and all its siblings. Safe to call on nil.
[ "AddChild", "adds", "a", "child", "part", "to", "either", "FirstChild", "or", "the", "end", "of", "the", "children", "NextSibling", "chain", ".", "The", "child", "may", "have", "siblings", "and", "children", "attached", ".", "This", "method", "will", "set", "the", "Parent", "field", "on", "child", "and", "all", "its", "siblings", ".", "Safe", "to", "call", "on", "nil", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L57-L87
test
jhillyerd/enmime
part.go
TextContent
func (p *Part) TextContent() bool { if p.ContentType == "" { // RFC 2045: no CT is equivalent to "text/plain; charset=us-ascii" return true } return strings.HasPrefix(p.ContentType, "text/") || strings.HasPrefix(p.ContentType, ctMultipartPrefix) }
go
func (p *Part) TextContent() bool { if p.ContentType == "" { // RFC 2045: no CT is equivalent to "text/plain; charset=us-ascii" return true } return strings.HasPrefix(p.ContentType, "text/") || strings.HasPrefix(p.ContentType, ctMultipartPrefix) }
[ "func", "(", "p", "*", "Part", ")", "TextContent", "(", ")", "bool", "{", "if", "p", ".", "ContentType", "==", "\"\"", "{", "return", "true", "\n", "}", "\n", "return", "strings", ".", "HasPrefix", "(", "p", ".", "ContentType", ",", "\"text/\"", ")", "||", "strings", ".", "HasPrefix", "(", "p", ".", "ContentType", ",", "ctMultipartPrefix", ")", "\n", "}" ]
// TextContent indicates whether the content is text based on its content type. This value // determines what content transfer encoding scheme to use.
[ "TextContent", "indicates", "whether", "the", "content", "is", "text", "based", "on", "its", "content", "type", ".", "This", "value", "determines", "what", "content", "transfer", "encoding", "scheme", "to", "use", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L91-L98
test
jhillyerd/enmime
part.go
setupHeaders
func (p *Part) setupHeaders(r *bufio.Reader, defaultContentType string) error { header, err := readHeader(r, p) if err != nil { return err } p.Header = header ctype := header.Get(hnContentType) if ctype == "" { if defaultContentType == "" { p.addWarning(ErrorMissingContentType, "MIME parts should have a Content-Type header") return nil } ctype = defaultContentType } // Parse Content-Type header. mtype, mparams, minvalidParams, err := parseMediaType(ctype) if err != nil { return err } if mtype == "" && len(mparams) > 0 { p.addWarning( ErrorMissingContentType, "Content-Type header has parameters but no content type") } for i := range minvalidParams { p.addWarning( ErrorMalformedHeader, "Content-Type header has malformed parameter %q", minvalidParams[i]) } p.ContentType = mtype // Set disposition, filename, charset if available. p.setupContentHeaders(mparams) p.Boundary = mparams[hpBoundary] p.ContentID = coding.FromIDHeader(header.Get(hnContentID)) return nil }
go
func (p *Part) setupHeaders(r *bufio.Reader, defaultContentType string) error { header, err := readHeader(r, p) if err != nil { return err } p.Header = header ctype := header.Get(hnContentType) if ctype == "" { if defaultContentType == "" { p.addWarning(ErrorMissingContentType, "MIME parts should have a Content-Type header") return nil } ctype = defaultContentType } // Parse Content-Type header. mtype, mparams, minvalidParams, err := parseMediaType(ctype) if err != nil { return err } if mtype == "" && len(mparams) > 0 { p.addWarning( ErrorMissingContentType, "Content-Type header has parameters but no content type") } for i := range minvalidParams { p.addWarning( ErrorMalformedHeader, "Content-Type header has malformed parameter %q", minvalidParams[i]) } p.ContentType = mtype // Set disposition, filename, charset if available. p.setupContentHeaders(mparams) p.Boundary = mparams[hpBoundary] p.ContentID = coding.FromIDHeader(header.Get(hnContentID)) return nil }
[ "func", "(", "p", "*", "Part", ")", "setupHeaders", "(", "r", "*", "bufio", ".", "Reader", ",", "defaultContentType", "string", ")", "error", "{", "header", ",", "err", ":=", "readHeader", "(", "r", ",", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "Header", "=", "header", "\n", "ctype", ":=", "header", ".", "Get", "(", "hnContentType", ")", "\n", "if", "ctype", "==", "\"\"", "{", "if", "defaultContentType", "==", "\"\"", "{", "p", ".", "addWarning", "(", "ErrorMissingContentType", ",", "\"MIME parts should have a Content-Type header\"", ")", "\n", "return", "nil", "\n", "}", "\n", "ctype", "=", "defaultContentType", "\n", "}", "\n", "mtype", ",", "mparams", ",", "minvalidParams", ",", "err", ":=", "parseMediaType", "(", "ctype", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "mtype", "==", "\"\"", "&&", "len", "(", "mparams", ")", ">", "0", "{", "p", ".", "addWarning", "(", "ErrorMissingContentType", ",", "\"Content-Type header has parameters but no content type\"", ")", "\n", "}", "\n", "for", "i", ":=", "range", "minvalidParams", "{", "p", ".", "addWarning", "(", "ErrorMalformedHeader", ",", "\"Content-Type header has malformed parameter %q\"", ",", "minvalidParams", "[", "i", "]", ")", "\n", "}", "\n", "p", ".", "ContentType", "=", "mtype", "\n", "p", ".", "setupContentHeaders", "(", "mparams", ")", "\n", "p", ".", "Boundary", "=", "mparams", "[", "hpBoundary", "]", "\n", "p", ".", "ContentID", "=", "coding", ".", "FromIDHeader", "(", "header", ".", "Get", "(", "hnContentID", ")", ")", "\n", "return", "nil", "\n", "}" ]
// setupHeaders reads the header, then populates the MIME header values for this Part.
[ "setupHeaders", "reads", "the", "header", "then", "populates", "the", "MIME", "header", "values", "for", "this", "Part", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L101-L137
test
jhillyerd/enmime
part.go
setupContentHeaders
func (p *Part) setupContentHeaders(mediaParams map[string]string) { // Determine content disposition, filename, character set. disposition, dparams, _, err := parseMediaType(p.Header.Get(hnContentDisposition)) if err == nil { // Disposition is optional p.Disposition = disposition p.FileName = decodeHeader(dparams[hpFilename]) } if p.FileName == "" && mediaParams[hpName] != "" { p.FileName = decodeHeader(mediaParams[hpName]) } if p.FileName == "" && mediaParams[hpFile] != "" { p.FileName = decodeHeader(mediaParams[hpFile]) } if p.Charset == "" { p.Charset = mediaParams[hpCharset] } if p.FileModDate.IsZero() { p.FileModDate, _ = time.Parse(time.RFC822, mediaParams[hpModDate]) } }
go
func (p *Part) setupContentHeaders(mediaParams map[string]string) { // Determine content disposition, filename, character set. disposition, dparams, _, err := parseMediaType(p.Header.Get(hnContentDisposition)) if err == nil { // Disposition is optional p.Disposition = disposition p.FileName = decodeHeader(dparams[hpFilename]) } if p.FileName == "" && mediaParams[hpName] != "" { p.FileName = decodeHeader(mediaParams[hpName]) } if p.FileName == "" && mediaParams[hpFile] != "" { p.FileName = decodeHeader(mediaParams[hpFile]) } if p.Charset == "" { p.Charset = mediaParams[hpCharset] } if p.FileModDate.IsZero() { p.FileModDate, _ = time.Parse(time.RFC822, mediaParams[hpModDate]) } }
[ "func", "(", "p", "*", "Part", ")", "setupContentHeaders", "(", "mediaParams", "map", "[", "string", "]", "string", ")", "{", "disposition", ",", "dparams", ",", "_", ",", "err", ":=", "parseMediaType", "(", "p", ".", "Header", ".", "Get", "(", "hnContentDisposition", ")", ")", "\n", "if", "err", "==", "nil", "{", "p", ".", "Disposition", "=", "disposition", "\n", "p", ".", "FileName", "=", "decodeHeader", "(", "dparams", "[", "hpFilename", "]", ")", "\n", "}", "\n", "if", "p", ".", "FileName", "==", "\"\"", "&&", "mediaParams", "[", "hpName", "]", "!=", "\"\"", "{", "p", ".", "FileName", "=", "decodeHeader", "(", "mediaParams", "[", "hpName", "]", ")", "\n", "}", "\n", "if", "p", ".", "FileName", "==", "\"\"", "&&", "mediaParams", "[", "hpFile", "]", "!=", "\"\"", "{", "p", ".", "FileName", "=", "decodeHeader", "(", "mediaParams", "[", "hpFile", "]", ")", "\n", "}", "\n", "if", "p", ".", "Charset", "==", "\"\"", "{", "p", ".", "Charset", "=", "mediaParams", "[", "hpCharset", "]", "\n", "}", "\n", "if", "p", ".", "FileModDate", ".", "IsZero", "(", ")", "{", "p", ".", "FileModDate", ",", "_", "=", "time", ".", "Parse", "(", "time", ".", "RFC822", ",", "mediaParams", "[", "hpModDate", "]", ")", "\n", "}", "\n", "}" ]
// setupContentHeaders uses Content-Type media params and Content-Disposition headers to populate // the disposition, filename, and charset fields.
[ "setupContentHeaders", "uses", "Content", "-", "Type", "media", "params", "and", "Content", "-", "Disposition", "headers", "to", "populate", "the", "disposition", "filename", "and", "charset", "fields", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L141-L161
test
jhillyerd/enmime
part.go
convertFromDetectedCharset
func (p *Part) convertFromDetectedCharset(r io.Reader) (io.Reader, error) { // Attempt to detect character set from part content. var cd *chardet.Detector switch p.ContentType { case "text/html": cd = chardet.NewHtmlDetector() default: cd = chardet.NewTextDetector() } buf, err := ioutil.ReadAll(r) if err != nil { return nil, errors.WithStack(err) } cs, err := cd.DetectBest(buf) switch err { case nil: // Carry on case chardet.NotDetectedError: p.addWarning(ErrorCharsetDeclaration, "charset could not be detected: %v", err) default: return nil, errors.WithStack(err) } // Restore r. r = bytes.NewReader(buf) if cs == nil || cs.Confidence < minCharsetConfidence { // Low confidence, use declared character set. return p.convertFromStatedCharset(r), nil } // Confidence exceeded our threshold, use detected character set. if p.Charset != "" && !strings.EqualFold(cs.Charset, p.Charset) { p.addWarning(ErrorCharsetDeclaration, "declared charset %q, detected %q, confidence %d", p.Charset, cs.Charset, cs.Confidence) } reader, err := coding.NewCharsetReader(cs.Charset, r) if err != nil { // Failed to get a conversion reader. p.addWarning(ErrorCharsetConversion, err.Error()) } else { r = reader p.OrigCharset = p.Charset p.Charset = cs.Charset } return r, nil }
go
func (p *Part) convertFromDetectedCharset(r io.Reader) (io.Reader, error) { // Attempt to detect character set from part content. var cd *chardet.Detector switch p.ContentType { case "text/html": cd = chardet.NewHtmlDetector() default: cd = chardet.NewTextDetector() } buf, err := ioutil.ReadAll(r) if err != nil { return nil, errors.WithStack(err) } cs, err := cd.DetectBest(buf) switch err { case nil: // Carry on case chardet.NotDetectedError: p.addWarning(ErrorCharsetDeclaration, "charset could not be detected: %v", err) default: return nil, errors.WithStack(err) } // Restore r. r = bytes.NewReader(buf) if cs == nil || cs.Confidence < minCharsetConfidence { // Low confidence, use declared character set. return p.convertFromStatedCharset(r), nil } // Confidence exceeded our threshold, use detected character set. if p.Charset != "" && !strings.EqualFold(cs.Charset, p.Charset) { p.addWarning(ErrorCharsetDeclaration, "declared charset %q, detected %q, confidence %d", p.Charset, cs.Charset, cs.Confidence) } reader, err := coding.NewCharsetReader(cs.Charset, r) if err != nil { // Failed to get a conversion reader. p.addWarning(ErrorCharsetConversion, err.Error()) } else { r = reader p.OrigCharset = p.Charset p.Charset = cs.Charset } return r, nil }
[ "func", "(", "p", "*", "Part", ")", "convertFromDetectedCharset", "(", "r", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "var", "cd", "*", "chardet", ".", "Detector", "\n", "switch", "p", ".", "ContentType", "{", "case", "\"text/html\"", ":", "cd", "=", "chardet", ".", "NewHtmlDetector", "(", ")", "\n", "default", ":", "cd", "=", "chardet", ".", "NewTextDetector", "(", ")", "\n", "}", "\n", "buf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "WithStack", "(", "err", ")", "\n", "}", "\n", "cs", ",", "err", ":=", "cd", ".", "DetectBest", "(", "buf", ")", "\n", "switch", "err", "{", "case", "nil", ":", "case", "chardet", ".", "NotDetectedError", ":", "p", ".", "addWarning", "(", "ErrorCharsetDeclaration", ",", "\"charset could not be detected: %v\"", ",", "err", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "WithStack", "(", "err", ")", "\n", "}", "\n", "r", "=", "bytes", ".", "NewReader", "(", "buf", ")", "\n", "if", "cs", "==", "nil", "||", "cs", ".", "Confidence", "<", "minCharsetConfidence", "{", "return", "p", ".", "convertFromStatedCharset", "(", "r", ")", ",", "nil", "\n", "}", "\n", "if", "p", ".", "Charset", "!=", "\"\"", "&&", "!", "strings", ".", "EqualFold", "(", "cs", ".", "Charset", ",", "p", ".", "Charset", ")", "{", "p", ".", "addWarning", "(", "ErrorCharsetDeclaration", ",", "\"declared charset %q, detected %q, confidence %d\"", ",", "p", ".", "Charset", ",", "cs", ".", "Charset", ",", "cs", ".", "Confidence", ")", "\n", "}", "\n", "reader", ",", "err", ":=", "coding", ".", "NewCharsetReader", "(", "cs", ".", "Charset", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "addWarning", "(", "ErrorCharsetConversion", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "r", "=", "reader", "\n", "p", ".", "OrigCharset", "=", "p", ".", "Charset", "\n", "p", ".", "Charset", "=", "cs", ".", "Charset", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// convertFromDetectedCharset attempts to detect the character set for the given part, and returns // an io.Reader that will convert from that charset to UTF-8. If the charset cannot be detected, // this method adds a warning to the part and automatically falls back to using // `convertFromStatedCharset` and returns the reader from that method.
[ "convertFromDetectedCharset", "attempts", "to", "detect", "the", "character", "set", "for", "the", "given", "part", "and", "returns", "an", "io", ".", "Reader", "that", "will", "convert", "from", "that", "charset", "to", "UTF", "-", "8", ".", "If", "the", "charset", "cannot", "be", "detected", "this", "method", "adds", "a", "warning", "to", "the", "part", "and", "automatically", "falls", "back", "to", "using", "convertFromStatedCharset", "and", "returns", "the", "reader", "from", "that", "method", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L167-L218
test
jhillyerd/enmime
part.go
Clone
func (p *Part) Clone(parent *Part) *Part { if p == nil { return nil } newPart := &Part{ PartID: p.PartID, Header: p.Header, Parent: parent, Boundary: p.Boundary, ContentID: p.ContentID, ContentType: p.ContentType, Disposition: p.Disposition, FileName: p.FileName, Charset: p.Charset, Errors: p.Errors, Content: p.Content, Epilogue: p.Epilogue, } newPart.FirstChild = p.FirstChild.Clone(newPart) newPart.NextSibling = p.NextSibling.Clone(parent) return newPart }
go
func (p *Part) Clone(parent *Part) *Part { if p == nil { return nil } newPart := &Part{ PartID: p.PartID, Header: p.Header, Parent: parent, Boundary: p.Boundary, ContentID: p.ContentID, ContentType: p.ContentType, Disposition: p.Disposition, FileName: p.FileName, Charset: p.Charset, Errors: p.Errors, Content: p.Content, Epilogue: p.Epilogue, } newPart.FirstChild = p.FirstChild.Clone(newPart) newPart.NextSibling = p.NextSibling.Clone(parent) return newPart }
[ "func", "(", "p", "*", "Part", ")", "Clone", "(", "parent", "*", "Part", ")", "*", "Part", "{", "if", "p", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "newPart", ":=", "&", "Part", "{", "PartID", ":", "p", ".", "PartID", ",", "Header", ":", "p", ".", "Header", ",", "Parent", ":", "parent", ",", "Boundary", ":", "p", ".", "Boundary", ",", "ContentID", ":", "p", ".", "ContentID", ",", "ContentType", ":", "p", ".", "ContentType", ",", "Disposition", ":", "p", ".", "Disposition", ",", "FileName", ":", "p", ".", "FileName", ",", "Charset", ":", "p", ".", "Charset", ",", "Errors", ":", "p", ".", "Errors", ",", "Content", ":", "p", ".", "Content", ",", "Epilogue", ":", "p", ".", "Epilogue", ",", "}", "\n", "newPart", ".", "FirstChild", "=", "p", ".", "FirstChild", ".", "Clone", "(", "newPart", ")", "\n", "newPart", ".", "NextSibling", "=", "p", ".", "NextSibling", ".", "Clone", "(", "parent", ")", "\n", "return", "newPart", "\n", "}" ]
// Clone returns a clone of the current Part.
[ "Clone", "returns", "a", "clone", "of", "the", "current", "Part", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L310-L333
test
jhillyerd/enmime
part.go
ReadParts
func ReadParts(r io.Reader) (*Part, error) { br := bufio.NewReader(r) root := &Part{PartID: "0"} // Read header; top-level default CT is text/plain us-ascii according to RFC 822. err := root.setupHeaders(br, `text/plain; charset="us-ascii"`) if err != nil { return nil, err } if strings.HasPrefix(root.ContentType, ctMultipartPrefix) { // Content is multipart, parse it. err = parseParts(root, br) if err != nil { return nil, err } } else { // Content is text or data, decode it. if err := root.decodeContent(br); err != nil { return nil, err } } return root, nil }
go
func ReadParts(r io.Reader) (*Part, error) { br := bufio.NewReader(r) root := &Part{PartID: "0"} // Read header; top-level default CT is text/plain us-ascii according to RFC 822. err := root.setupHeaders(br, `text/plain; charset="us-ascii"`) if err != nil { return nil, err } if strings.HasPrefix(root.ContentType, ctMultipartPrefix) { // Content is multipart, parse it. err = parseParts(root, br) if err != nil { return nil, err } } else { // Content is text or data, decode it. if err := root.decodeContent(br); err != nil { return nil, err } } return root, nil }
[ "func", "ReadParts", "(", "r", "io", ".", "Reader", ")", "(", "*", "Part", ",", "error", ")", "{", "br", ":=", "bufio", ".", "NewReader", "(", "r", ")", "\n", "root", ":=", "&", "Part", "{", "PartID", ":", "\"0\"", "}", "\n", "err", ":=", "root", ".", "setupHeaders", "(", "br", ",", "`text/plain; charset=\"us-ascii\"`", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "root", ".", "ContentType", ",", "ctMultipartPrefix", ")", "{", "err", "=", "parseParts", "(", "root", ",", "br", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "root", ".", "decodeContent", "(", "br", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "root", ",", "nil", "\n", "}" ]
// ReadParts reads a MIME document from the provided reader and parses it into tree of Part objects.
[ "ReadParts", "reads", "a", "MIME", "document", "from", "the", "provided", "reader", "and", "parses", "it", "into", "tree", "of", "Part", "objects", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L336-L357
test
jhillyerd/enmime
part.go
parseParts
func parseParts(parent *Part, reader *bufio.Reader) error { firstRecursion := parent.Parent == nil // Loop over MIME boundaries. br := newBoundaryReader(reader, parent.Boundary) for indexPartID := 1; true; indexPartID++ { next, err := br.Next() if err != nil && errors.Cause(err) != io.EOF { return err } if !next { break } p := &Part{} // Set this Part's PartID, indicating its position within the MIME Part tree. if firstRecursion { p.PartID = strconv.Itoa(indexPartID) } else { p.PartID = parent.PartID + "." + strconv.Itoa(indexPartID) } // Look for part header. bbr := bufio.NewReader(br) err = p.setupHeaders(bbr, "") if errors.Cause(err) == errEmptyHeaderBlock { // Empty header probably means the part didn't use the correct trailing "--" syntax to // close its boundary. if _, err = br.Next(); err != nil { if errors.Cause(err) == io.EOF || strings.HasSuffix(err.Error(), "EOF") { // There are no more Parts. The error must belong to the parent, because this // part doesn't exist. parent.addWarning(ErrorMissingBoundary, "Boundary %q was not closed correctly", parent.Boundary) break } // The error is already wrapped with a stack, so only adding a message here. // TODO: Once `errors` releases a version > v0.8.0, change to use errors.WithMessagef() return errors.WithMessage(err, fmt.Sprintf("error at boundary %v", parent.Boundary)) } } else if err != nil { return err } // Insert this Part into the MIME tree. parent.AddChild(p) if p.Boundary == "" { // Content is text or data, decode it. if err := p.decodeContent(bbr); err != nil { return err } } else { // Content is another multipart. err = parseParts(p, bbr) if err != nil { return err } } } // Store any content following the closing boundary marker into the epilogue. epilogue, err := ioutil.ReadAll(reader) if err != nil { return errors.WithStack(err) } parent.Epilogue = epilogue // If a Part is "multipart/" Content-Type, it will have .0 appended to its PartID // i.e. it is the root of its MIME Part subtree. if !firstRecursion { parent.PartID += ".0" } return nil }
go
func parseParts(parent *Part, reader *bufio.Reader) error { firstRecursion := parent.Parent == nil // Loop over MIME boundaries. br := newBoundaryReader(reader, parent.Boundary) for indexPartID := 1; true; indexPartID++ { next, err := br.Next() if err != nil && errors.Cause(err) != io.EOF { return err } if !next { break } p := &Part{} // Set this Part's PartID, indicating its position within the MIME Part tree. if firstRecursion { p.PartID = strconv.Itoa(indexPartID) } else { p.PartID = parent.PartID + "." + strconv.Itoa(indexPartID) } // Look for part header. bbr := bufio.NewReader(br) err = p.setupHeaders(bbr, "") if errors.Cause(err) == errEmptyHeaderBlock { // Empty header probably means the part didn't use the correct trailing "--" syntax to // close its boundary. if _, err = br.Next(); err != nil { if errors.Cause(err) == io.EOF || strings.HasSuffix(err.Error(), "EOF") { // There are no more Parts. The error must belong to the parent, because this // part doesn't exist. parent.addWarning(ErrorMissingBoundary, "Boundary %q was not closed correctly", parent.Boundary) break } // The error is already wrapped with a stack, so only adding a message here. // TODO: Once `errors` releases a version > v0.8.0, change to use errors.WithMessagef() return errors.WithMessage(err, fmt.Sprintf("error at boundary %v", parent.Boundary)) } } else if err != nil { return err } // Insert this Part into the MIME tree. parent.AddChild(p) if p.Boundary == "" { // Content is text or data, decode it. if err := p.decodeContent(bbr); err != nil { return err } } else { // Content is another multipart. err = parseParts(p, bbr) if err != nil { return err } } } // Store any content following the closing boundary marker into the epilogue. epilogue, err := ioutil.ReadAll(reader) if err != nil { return errors.WithStack(err) } parent.Epilogue = epilogue // If a Part is "multipart/" Content-Type, it will have .0 appended to its PartID // i.e. it is the root of its MIME Part subtree. if !firstRecursion { parent.PartID += ".0" } return nil }
[ "func", "parseParts", "(", "parent", "*", "Part", ",", "reader", "*", "bufio", ".", "Reader", ")", "error", "{", "firstRecursion", ":=", "parent", ".", "Parent", "==", "nil", "\n", "br", ":=", "newBoundaryReader", "(", "reader", ",", "parent", ".", "Boundary", ")", "\n", "for", "indexPartID", ":=", "1", ";", "true", ";", "indexPartID", "++", "{", "next", ",", "err", ":=", "br", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "errors", ".", "Cause", "(", "err", ")", "!=", "io", ".", "EOF", "{", "return", "err", "\n", "}", "\n", "if", "!", "next", "{", "break", "\n", "}", "\n", "p", ":=", "&", "Part", "{", "}", "\n", "if", "firstRecursion", "{", "p", ".", "PartID", "=", "strconv", ".", "Itoa", "(", "indexPartID", ")", "\n", "}", "else", "{", "p", ".", "PartID", "=", "parent", ".", "PartID", "+", "\".\"", "+", "strconv", ".", "Itoa", "(", "indexPartID", ")", "\n", "}", "\n", "bbr", ":=", "bufio", ".", "NewReader", "(", "br", ")", "\n", "err", "=", "p", ".", "setupHeaders", "(", "bbr", ",", "\"\"", ")", "\n", "if", "errors", ".", "Cause", "(", "err", ")", "==", "errEmptyHeaderBlock", "{", "if", "_", ",", "err", "=", "br", ".", "Next", "(", ")", ";", "err", "!=", "nil", "{", "if", "errors", ".", "Cause", "(", "err", ")", "==", "io", ".", "EOF", "||", "strings", ".", "HasSuffix", "(", "err", ".", "Error", "(", ")", ",", "\"EOF\"", ")", "{", "parent", ".", "addWarning", "(", "ErrorMissingBoundary", ",", "\"Boundary %q was not closed correctly\"", ",", "parent", ".", "Boundary", ")", "\n", "break", "\n", "}", "\n", "return", "errors", ".", "WithMessage", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"error at boundary %v\"", ",", "parent", ".", "Boundary", ")", ")", "\n", "}", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "parent", ".", "AddChild", "(", "p", ")", "\n", "if", "p", ".", "Boundary", "==", "\"\"", "{", "if", "err", ":=", "p", ".", "decodeContent", "(", "bbr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "err", "=", "parseParts", "(", "p", ",", "bbr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "epilogue", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "WithStack", "(", "err", ")", "\n", "}", "\n", "parent", ".", "Epilogue", "=", "epilogue", "\n", "if", "!", "firstRecursion", "{", "parent", ".", "PartID", "+=", "\".0\"", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// parseParts recursively parses a MIME multipart document and sets each Parts PartID.
[ "parseParts", "recursively", "parses", "a", "MIME", "multipart", "document", "and", "sets", "each", "Parts", "PartID", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L360-L427
test
jhillyerd/enmime
internal/stringutil/uuid.go
UUID
func UUID() string { uuid := make([]byte, 16) uuidMutex.Lock() _, _ = uuidRand.Read(uuid) uuidMutex.Unlock() // variant bits; see section 4.1.1 uuid[8] = uuid[8]&^0xc0 | 0x80 // version 4 (pseudo-random); see section 4.1.3 uuid[6] = uuid[6]&^0xf0 | 0x40 return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]) }
go
func UUID() string { uuid := make([]byte, 16) uuidMutex.Lock() _, _ = uuidRand.Read(uuid) uuidMutex.Unlock() // variant bits; see section 4.1.1 uuid[8] = uuid[8]&^0xc0 | 0x80 // version 4 (pseudo-random); see section 4.1.3 uuid[6] = uuid[6]&^0xf0 | 0x40 return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]) }
[ "func", "UUID", "(", ")", "string", "{", "uuid", ":=", "make", "(", "[", "]", "byte", ",", "16", ")", "\n", "uuidMutex", ".", "Lock", "(", ")", "\n", "_", ",", "_", "=", "uuidRand", ".", "Read", "(", "uuid", ")", "\n", "uuidMutex", ".", "Unlock", "(", ")", "\n", "uuid", "[", "8", "]", "=", "uuid", "[", "8", "]", "&^", "0xc0", "|", "0x80", "\n", "uuid", "[", "6", "]", "=", "uuid", "[", "6", "]", "&^", "0xf0", "|", "0x40", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%x-%x-%x-%x-%x\"", ",", "uuid", "[", "0", ":", "4", "]", ",", "uuid", "[", "4", ":", "6", "]", ",", "uuid", "[", "6", ":", "8", "]", ",", "uuid", "[", "8", ":", "10", "]", ",", "uuid", "[", "10", ":", "]", ")", "\n", "}" ]
// UUID generates a random UUID according to RFC 4122.
[ "UUID", "generates", "a", "random", "UUID", "according", "to", "RFC", "4122", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/stringutil/uuid.go#L14-L24
test
jhillyerd/enmime
internal/coding/quotedprint.go
NewQPCleaner
func NewQPCleaner(r io.Reader) *QPCleaner { return &QPCleaner{ in: bufio.NewReader(r), } }
go
func NewQPCleaner(r io.Reader) *QPCleaner { return &QPCleaner{ in: bufio.NewReader(r), } }
[ "func", "NewQPCleaner", "(", "r", "io", ".", "Reader", ")", "*", "QPCleaner", "{", "return", "&", "QPCleaner", "{", "in", ":", "bufio", ".", "NewReader", "(", "r", ")", ",", "}", "\n", "}" ]
// NewQPCleaner returns a QPCleaner for the specified reader.
[ "NewQPCleaner", "returns", "a", "QPCleaner", "for", "the", "specified", "reader", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/coding/quotedprint.go#L19-L23
test
jhillyerd/enmime
error.go
Error
func (e *Error) Error() string { sev := "W" if e.Severe { sev = "E" } return fmt.Sprintf("[%s] %s: %s", sev, e.Name, e.Detail) }
go
func (e *Error) Error() string { sev := "W" if e.Severe { sev = "E" } return fmt.Sprintf("[%s] %s: %s", sev, e.Name, e.Detail) }
[ "func", "(", "e", "*", "Error", ")", "Error", "(", ")", "string", "{", "sev", ":=", "\"W\"", "\n", "if", "e", ".", "Severe", "{", "sev", "=", "\"E\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"[%s] %s: %s\"", ",", "sev", ",", "e", ".", "Name", ",", "e", ".", "Detail", ")", "\n", "}" ]
// Error formats the enmime.Error as a string.
[ "Error", "formats", "the", "enmime", ".", "Error", "as", "a", "string", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/error.go#L34-L40
test
jhillyerd/enmime
error.go
addError
func (p *Part) addError(name string, detailFmt string, args ...interface{}) { p.Errors = append( p.Errors, &Error{ name, fmt.Sprintf(detailFmt, args...), true, }) }
go
func (p *Part) addError(name string, detailFmt string, args ...interface{}) { p.Errors = append( p.Errors, &Error{ name, fmt.Sprintf(detailFmt, args...), true, }) }
[ "func", "(", "p", "*", "Part", ")", "addError", "(", "name", "string", ",", "detailFmt", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "p", ".", "Errors", "=", "append", "(", "p", ".", "Errors", ",", "&", "Error", "{", "name", ",", "fmt", ".", "Sprintf", "(", "detailFmt", ",", "args", "...", ")", ",", "true", ",", "}", ")", "\n", "}" ]
// addWarning builds a severe Error and appends to the Part error slice.
[ "addWarning", "builds", "a", "severe", "Error", "and", "appends", "to", "the", "Part", "error", "slice", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/error.go#L48-L56
test
jhillyerd/enmime
error.go
addWarning
func (p *Part) addWarning(name string, detailFmt string, args ...interface{}) { p.Errors = append( p.Errors, &Error{ name, fmt.Sprintf(detailFmt, args...), false, }) }
go
func (p *Part) addWarning(name string, detailFmt string, args ...interface{}) { p.Errors = append( p.Errors, &Error{ name, fmt.Sprintf(detailFmt, args...), false, }) }
[ "func", "(", "p", "*", "Part", ")", "addWarning", "(", "name", "string", ",", "detailFmt", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "p", ".", "Errors", "=", "append", "(", "p", ".", "Errors", ",", "&", "Error", "{", "name", ",", "fmt", ".", "Sprintf", "(", "detailFmt", ",", "args", "...", ")", ",", "false", ",", "}", ")", "\n", "}" ]
// addWarning builds a non-severe Error and appends to the Part error slice.
[ "addWarning", "builds", "a", "non", "-", "severe", "Error", "and", "appends", "to", "the", "Part", "error", "slice", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/error.go#L59-L67
test
jhillyerd/enmime
internal/stringutil/wrap.go
Wrap
func Wrap(max int, strs ...string) []byte { input := make([]byte, 0) output := make([]byte, 0) for _, s := range strs { input = append(input, []byte(s)...) } if len(input) < max { // Doesn't need to be wrapped return input } ls := -1 // Last seen space index lw := -1 // Last written byte index ll := 0 // Length of current line for i := 0; i < len(input); i++ { ll++ switch input[i] { case ' ', '\t': ls = i } if ll >= max { if ls >= 0 { output = append(output, input[lw+1:ls]...) output = append(output, '\r', '\n', ' ') lw = ls // Jump over the space we broke on ll = 1 // Count leading space above // Rewind i = lw + 1 ls = -1 } } } return append(output, input[lw+1:]...) }
go
func Wrap(max int, strs ...string) []byte { input := make([]byte, 0) output := make([]byte, 0) for _, s := range strs { input = append(input, []byte(s)...) } if len(input) < max { // Doesn't need to be wrapped return input } ls := -1 // Last seen space index lw := -1 // Last written byte index ll := 0 // Length of current line for i := 0; i < len(input); i++ { ll++ switch input[i] { case ' ', '\t': ls = i } if ll >= max { if ls >= 0 { output = append(output, input[lw+1:ls]...) output = append(output, '\r', '\n', ' ') lw = ls // Jump over the space we broke on ll = 1 // Count leading space above // Rewind i = lw + 1 ls = -1 } } } return append(output, input[lw+1:]...) }
[ "func", "Wrap", "(", "max", "int", ",", "strs", "...", "string", ")", "[", "]", "byte", "{", "input", ":=", "make", "(", "[", "]", "byte", ",", "0", ")", "\n", "output", ":=", "make", "(", "[", "]", "byte", ",", "0", ")", "\n", "for", "_", ",", "s", ":=", "range", "strs", "{", "input", "=", "append", "(", "input", ",", "[", "]", "byte", "(", "s", ")", "...", ")", "\n", "}", "\n", "if", "len", "(", "input", ")", "<", "max", "{", "return", "input", "\n", "}", "\n", "ls", ":=", "-", "1", "\n", "lw", ":=", "-", "1", "\n", "ll", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "input", ")", ";", "i", "++", "{", "ll", "++", "\n", "switch", "input", "[", "i", "]", "{", "case", "' '", ",", "'\\t'", ":", "ls", "=", "i", "\n", "}", "\n", "if", "ll", ">=", "max", "{", "if", "ls", ">=", "0", "{", "output", "=", "append", "(", "output", ",", "input", "[", "lw", "+", "1", ":", "ls", "]", "...", ")", "\n", "output", "=", "append", "(", "output", ",", "'\\r'", ",", "'\\n'", ",", "' '", ")", "\n", "lw", "=", "ls", "\n", "ll", "=", "1", "\n", "i", "=", "lw", "+", "1", "\n", "ls", "=", "-", "1", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "append", "(", "output", ",", "input", "[", "lw", "+", "1", ":", "]", "...", ")", "\n", "}" ]
// Wrap builds a byte slice from strs, wrapping on word boundaries before max chars
[ "Wrap", "builds", "a", "byte", "slice", "from", "strs", "wrapping", "on", "word", "boundaries", "before", "max", "chars" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/stringutil/wrap.go#L4-L36
test
jhillyerd/enmime
internal/coding/charsets.go
ConvertToUTF8String
func ConvertToUTF8String(charset string, textBytes []byte) (string, error) { if strings.ToLower(charset) == utf8 { return string(textBytes), nil } csentry, ok := encodings[strings.ToLower(charset)] if !ok { return "", fmt.Errorf("Unsupported charset %q", charset) } input := bytes.NewReader(textBytes) reader := transform.NewReader(input, csentry.e.NewDecoder()) output, err := ioutil.ReadAll(reader) if err != nil { return "", err } return string(output), nil }
go
func ConvertToUTF8String(charset string, textBytes []byte) (string, error) { if strings.ToLower(charset) == utf8 { return string(textBytes), nil } csentry, ok := encodings[strings.ToLower(charset)] if !ok { return "", fmt.Errorf("Unsupported charset %q", charset) } input := bytes.NewReader(textBytes) reader := transform.NewReader(input, csentry.e.NewDecoder()) output, err := ioutil.ReadAll(reader) if err != nil { return "", err } return string(output), nil }
[ "func", "ConvertToUTF8String", "(", "charset", "string", ",", "textBytes", "[", "]", "byte", ")", "(", "string", ",", "error", ")", "{", "if", "strings", ".", "ToLower", "(", "charset", ")", "==", "utf8", "{", "return", "string", "(", "textBytes", ")", ",", "nil", "\n", "}", "\n", "csentry", ",", "ok", ":=", "encodings", "[", "strings", ".", "ToLower", "(", "charset", ")", "]", "\n", "if", "!", "ok", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"Unsupported charset %q\"", ",", "charset", ")", "\n", "}", "\n", "input", ":=", "bytes", ".", "NewReader", "(", "textBytes", ")", "\n", "reader", ":=", "transform", ".", "NewReader", "(", "input", ",", "csentry", ".", "e", ".", "NewDecoder", "(", ")", ")", "\n", "output", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "output", ")", ",", "nil", "\n", "}" ]
// ConvertToUTF8String uses the provided charset to decode a slice of bytes into a normal // UTF-8 string.
[ "ConvertToUTF8String", "uses", "the", "provided", "charset", "to", "decode", "a", "slice", "of", "bytes", "into", "a", "normal", "UTF", "-", "8", "string", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/coding/charsets.go#L272-L287
test
jhillyerd/enmime
internal/stringutil/addr.go
JoinAddress
func JoinAddress(addrs []mail.Address) string { if len(addrs) == 0 { return "" } buf := &bytes.Buffer{} for i, a := range addrs { if i > 0 { _, _ = buf.WriteString(", ") } _, _ = buf.WriteString(a.String()) } return buf.String() }
go
func JoinAddress(addrs []mail.Address) string { if len(addrs) == 0 { return "" } buf := &bytes.Buffer{} for i, a := range addrs { if i > 0 { _, _ = buf.WriteString(", ") } _, _ = buf.WriteString(a.String()) } return buf.String() }
[ "func", "JoinAddress", "(", "addrs", "[", "]", "mail", ".", "Address", ")", "string", "{", "if", "len", "(", "addrs", ")", "==", "0", "{", "return", "\"\"", "\n", "}", "\n", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "for", "i", ",", "a", ":=", "range", "addrs", "{", "if", "i", ">", "0", "{", "_", ",", "_", "=", "buf", ".", "WriteString", "(", "\", \"", ")", "\n", "}", "\n", "_", ",", "_", "=", "buf", ".", "WriteString", "(", "a", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// JoinAddress formats a slice of Address structs such that they can be used in a To or Cc header.
[ "JoinAddress", "formats", "a", "slice", "of", "Address", "structs", "such", "that", "they", "can", "be", "used", "in", "a", "To", "or", "Cc", "header", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/stringutil/addr.go#L9-L21
test
jhillyerd/enmime
cmd/utils.go
Printf
func (md *markdown) Printf(format string, args ...interface{}) { fmt.Fprintf(md, format, args...) }
go
func (md *markdown) Printf(format string, args ...interface{}) { fmt.Fprintf(md, format, args...) }
[ "func", "(", "md", "*", "markdown", ")", "Printf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Fprintf", "(", "md", ",", "format", ",", "args", "...", ")", "\n", "}" ]
// Printf implements fmt.Printf for markdown
[ "Printf", "implements", "fmt", ".", "Printf", "for", "markdown" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/cmd/utils.go#L36-L38
test
jhillyerd/enmime
cmd/utils.go
EnvelopeToMarkdown
func EnvelopeToMarkdown(w io.Writer, e *enmime.Envelope, name string) error { md := &markdown{bufio.NewWriter(w)} md.H1(name) // Output a sorted list of headers, minus the ones displayed later md.H2("Header") if e.Root != nil && e.Root.Header != nil { keys := make([]string, 0, len(e.Root.Header)) for k := range e.Root.Header { switch strings.ToLower(k) { case "from", "to", "cc", "bcc", "reply-to", "subject": continue } keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { md.Printf(" %v: %v\n", k, e.GetHeader(k)) } } md.Println() md.H2("Envelope") for _, hkey := range addressHeaders { addrlist, err := e.AddressList(hkey) if err != nil { if err == mail.ErrHeaderNotPresent { continue } return err } md.H3(hkey) for _, addr := range addrlist { md.Printf("- %v `<%v>`\n", addr.Name, addr.Address) } md.Println() } md.H3("Subject") md.Println(e.GetHeader("Subject")) md.Println() md.H2("Body Text") md.Println(e.Text) md.Println() md.H2("Body HTML") md.Println(e.HTML) md.Println() md.H2("Attachment List") for _, a := range e.Attachments { md.Printf("- %v (%v)\n", a.FileName, a.ContentType) if a.ContentID != "" { md.Printf(" Content-ID: %s\n", a.ContentID) } } md.Println() md.H2("Inline List") for _, a := range e.Inlines { md.Printf("- %v (%v)\n", a.FileName, a.ContentType) if a.ContentID != "" { md.Printf(" Content-ID: %s\n", a.ContentID) } } md.Println() md.H2("Other Part List") for _, a := range e.OtherParts { md.Printf("- %v (%v)\n", a.FileName, a.ContentType) if a.ContentID != "" { md.Printf(" Content-ID: %s\n", a.ContentID) } } md.Println() md.H2("MIME Part Tree") if e.Root == nil { md.Println("Message was not MIME encoded") } else { FormatPart(md, e.Root, " ") } if len(e.Errors) > 0 { md.Println() md.H2("Errors") for _, perr := range e.Errors { md.Println("-", perr) } } return md.Flush() }
go
func EnvelopeToMarkdown(w io.Writer, e *enmime.Envelope, name string) error { md := &markdown{bufio.NewWriter(w)} md.H1(name) // Output a sorted list of headers, minus the ones displayed later md.H2("Header") if e.Root != nil && e.Root.Header != nil { keys := make([]string, 0, len(e.Root.Header)) for k := range e.Root.Header { switch strings.ToLower(k) { case "from", "to", "cc", "bcc", "reply-to", "subject": continue } keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { md.Printf(" %v: %v\n", k, e.GetHeader(k)) } } md.Println() md.H2("Envelope") for _, hkey := range addressHeaders { addrlist, err := e.AddressList(hkey) if err != nil { if err == mail.ErrHeaderNotPresent { continue } return err } md.H3(hkey) for _, addr := range addrlist { md.Printf("- %v `<%v>`\n", addr.Name, addr.Address) } md.Println() } md.H3("Subject") md.Println(e.GetHeader("Subject")) md.Println() md.H2("Body Text") md.Println(e.Text) md.Println() md.H2("Body HTML") md.Println(e.HTML) md.Println() md.H2("Attachment List") for _, a := range e.Attachments { md.Printf("- %v (%v)\n", a.FileName, a.ContentType) if a.ContentID != "" { md.Printf(" Content-ID: %s\n", a.ContentID) } } md.Println() md.H2("Inline List") for _, a := range e.Inlines { md.Printf("- %v (%v)\n", a.FileName, a.ContentType) if a.ContentID != "" { md.Printf(" Content-ID: %s\n", a.ContentID) } } md.Println() md.H2("Other Part List") for _, a := range e.OtherParts { md.Printf("- %v (%v)\n", a.FileName, a.ContentType) if a.ContentID != "" { md.Printf(" Content-ID: %s\n", a.ContentID) } } md.Println() md.H2("MIME Part Tree") if e.Root == nil { md.Println("Message was not MIME encoded") } else { FormatPart(md, e.Root, " ") } if len(e.Errors) > 0 { md.Println() md.H2("Errors") for _, perr := range e.Errors { md.Println("-", perr) } } return md.Flush() }
[ "func", "EnvelopeToMarkdown", "(", "w", "io", ".", "Writer", ",", "e", "*", "enmime", ".", "Envelope", ",", "name", "string", ")", "error", "{", "md", ":=", "&", "markdown", "{", "bufio", ".", "NewWriter", "(", "w", ")", "}", "\n", "md", ".", "H1", "(", "name", ")", "\n", "md", ".", "H2", "(", "\"Header\"", ")", "\n", "if", "e", ".", "Root", "!=", "nil", "&&", "e", ".", "Root", ".", "Header", "!=", "nil", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "e", ".", "Root", ".", "Header", ")", ")", "\n", "for", "k", ":=", "range", "e", ".", "Root", ".", "Header", "{", "switch", "strings", ".", "ToLower", "(", "k", ")", "{", "case", "\"from\"", ",", "\"to\"", ",", "\"cc\"", ",", "\"bcc\"", ",", "\"reply-to\"", ",", "\"subject\"", ":", "continue", "\n", "}", "\n", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "md", ".", "Printf", "(", "\" %v: %v\\n\"", ",", "\\n", ",", "k", ")", "\n", "}", "\n", "}", "\n", "e", ".", "GetHeader", "(", "k", ")", "\n", "md", ".", "Println", "(", ")", "\n", "md", ".", "H2", "(", "\"Envelope\"", ")", "\n", "for", "_", ",", "hkey", ":=", "range", "addressHeaders", "{", "addrlist", ",", "err", ":=", "e", ".", "AddressList", "(", "hkey", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "mail", ".", "ErrHeaderNotPresent", "{", "continue", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "md", ".", "H3", "(", "hkey", ")", "\n", "for", "_", ",", "addr", ":=", "range", "addrlist", "{", "md", ".", "Printf", "(", "\"- %v `<%v>`\\n\"", ",", "\\n", ",", "addr", ".", "Name", ")", "\n", "}", "\n", "addr", ".", "Address", "\n", "}", "\n", "md", ".", "Println", "(", ")", "\n", "md", ".", "H3", "(", "\"Subject\"", ")", "\n", "md", ".", "Println", "(", "e", ".", "GetHeader", "(", "\"Subject\"", ")", ")", "\n", "md", ".", "Println", "(", ")", "\n", "md", ".", "H2", "(", "\"Body Text\"", ")", "\n", "md", ".", "Println", "(", "e", ".", "Text", ")", "\n", "md", ".", "Println", "(", ")", "\n", "md", ".", "H2", "(", "\"Body HTML\"", ")", "\n", "md", ".", "Println", "(", "e", ".", "HTML", ")", "\n", "md", ".", "Println", "(", ")", "\n", "md", ".", "H2", "(", "\"Attachment List\"", ")", "\n", "for", "_", ",", "a", ":=", "range", "e", ".", "Attachments", "{", "md", ".", "Printf", "(", "\"- %v (%v)\\n\"", ",", "\\n", ",", "a", ".", "FileName", ")", "\n", "a", ".", "ContentType", "\n", "}", "\n", "if", "a", ".", "ContentID", "!=", "\"\"", "{", "md", ".", "Printf", "(", "\" Content-ID: %s\\n\"", ",", "\\n", ")", "\n", "}", "\n", "a", ".", "ContentID", "\n", "md", ".", "Println", "(", ")", "\n", "md", ".", "H2", "(", "\"Inline List\"", ")", "\n", "for", "_", ",", "a", ":=", "range", "e", ".", "Inlines", "{", "md", ".", "Printf", "(", "\"- %v (%v)\\n\"", ",", "\\n", ",", "a", ".", "FileName", ")", "\n", "a", ".", "ContentType", "\n", "}", "\n", "if", "a", ".", "ContentID", "!=", "\"\"", "{", "md", ".", "Printf", "(", "\" Content-ID: %s\\n\"", ",", "\\n", ")", "\n", "}", "\n", "a", ".", "ContentID", "\n", "md", ".", "Println", "(", ")", "\n", "md", ".", "H2", "(", "\"Other Part List\"", ")", "\n", "}" ]
// EnvelopeToMarkdown renders the contents of an enmime.Envelope in Markdown format. Used by // mime-dump and mime-extractor commands.
[ "EnvelopeToMarkdown", "renders", "the", "contents", "of", "an", "enmime", ".", "Envelope", "in", "Markdown", "format", ".", "Used", "by", "mime", "-", "dump", "and", "mime", "-", "extractor", "commands", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/cmd/utils.go#L47-L140
test
jhillyerd/enmime
cmd/utils.go
FormatPart
func FormatPart(w io.Writer, p *enmime.Part, indent string) { if p == nil { return } sibling := p.NextSibling child := p.FirstChild // Compute indent strings myindent := indent + "`-- " childindent := indent + " " if sibling != nil { myindent = indent + "|-- " childindent = indent + "| " } if p.Parent == nil { // Root shouldn't be decorated, has no siblings myindent = indent childindent = indent } // Format and print this node ctype := "MISSING TYPE" if p.ContentType != "" { ctype = p.ContentType } disposition := "" if p.Disposition != "" { disposition = fmt.Sprintf(", disposition: %s", p.Disposition) } filename := "" if p.FileName != "" { filename = fmt.Sprintf(", filename: %q", p.FileName) } errors := "" if len(p.Errors) > 0 { errors = fmt.Sprintf(" (errors: %v)", len(p.Errors)) } fmt.Fprintf(w, "%s%s%s%s%s\n", myindent, ctype, disposition, filename, errors) // Recurse FormatPart(w, child, childindent) FormatPart(w, sibling, indent) }
go
func FormatPart(w io.Writer, p *enmime.Part, indent string) { if p == nil { return } sibling := p.NextSibling child := p.FirstChild // Compute indent strings myindent := indent + "`-- " childindent := indent + " " if sibling != nil { myindent = indent + "|-- " childindent = indent + "| " } if p.Parent == nil { // Root shouldn't be decorated, has no siblings myindent = indent childindent = indent } // Format and print this node ctype := "MISSING TYPE" if p.ContentType != "" { ctype = p.ContentType } disposition := "" if p.Disposition != "" { disposition = fmt.Sprintf(", disposition: %s", p.Disposition) } filename := "" if p.FileName != "" { filename = fmt.Sprintf(", filename: %q", p.FileName) } errors := "" if len(p.Errors) > 0 { errors = fmt.Sprintf(" (errors: %v)", len(p.Errors)) } fmt.Fprintf(w, "%s%s%s%s%s\n", myindent, ctype, disposition, filename, errors) // Recurse FormatPart(w, child, childindent) FormatPart(w, sibling, indent) }
[ "func", "FormatPart", "(", "w", "io", ".", "Writer", ",", "p", "*", "enmime", ".", "Part", ",", "indent", "string", ")", "{", "if", "p", "==", "nil", "{", "return", "\n", "}", "\n", "sibling", ":=", "p", ".", "NextSibling", "\n", "child", ":=", "p", ".", "FirstChild", "\n", "myindent", ":=", "indent", "+", "\"`-- \"", "\n", "childindent", ":=", "indent", "+", "\" \"", "\n", "if", "sibling", "!=", "nil", "{", "myindent", "=", "indent", "+", "\"|-- \"", "\n", "childindent", "=", "indent", "+", "\"| \"", "\n", "}", "\n", "if", "p", ".", "Parent", "==", "nil", "{", "myindent", "=", "indent", "\n", "childindent", "=", "indent", "\n", "}", "\n", "ctype", ":=", "\"MISSING TYPE\"", "\n", "if", "p", ".", "ContentType", "!=", "\"\"", "{", "ctype", "=", "p", ".", "ContentType", "\n", "}", "\n", "disposition", ":=", "\"\"", "\n", "if", "p", ".", "Disposition", "!=", "\"\"", "{", "disposition", "=", "fmt", ".", "Sprintf", "(", "\", disposition: %s\"", ",", "p", ".", "Disposition", ")", "\n", "}", "\n", "filename", ":=", "\"\"", "\n", "if", "p", ".", "FileName", "!=", "\"\"", "{", "filename", "=", "fmt", ".", "Sprintf", "(", "\", filename: %q\"", ",", "p", ".", "FileName", ")", "\n", "}", "\n", "errors", ":=", "\"\"", "\n", "if", "len", "(", "p", ".", "Errors", ")", ">", "0", "{", "errors", "=", "fmt", ".", "Sprintf", "(", "\" (errors: %v)\"", ",", "len", "(", "p", ".", "Errors", ")", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"%s%s%s%s%s\\n\"", ",", "\\n", ",", "myindent", ",", "ctype", ",", "disposition", ",", "filename", ")", "\n", "errors", "\n", "FormatPart", "(", "w", ",", "child", ",", "childindent", ")", "\n", "}" ]
// FormatPart pretty prints the Part tree
[ "FormatPart", "pretty", "prints", "the", "Part", "tree" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/cmd/utils.go#L143-L186
test
jhillyerd/enmime
boundary.go
newBoundaryReader
func newBoundaryReader(reader *bufio.Reader, boundary string) *boundaryReader { fullBoundary := []byte("\n--" + boundary + "--") return &boundaryReader{ r: reader, nlPrefix: fullBoundary[:len(fullBoundary)-2], prefix: fullBoundary[1 : len(fullBoundary)-2], final: fullBoundary[1:], buffer: new(bytes.Buffer), } }
go
func newBoundaryReader(reader *bufio.Reader, boundary string) *boundaryReader { fullBoundary := []byte("\n--" + boundary + "--") return &boundaryReader{ r: reader, nlPrefix: fullBoundary[:len(fullBoundary)-2], prefix: fullBoundary[1 : len(fullBoundary)-2], final: fullBoundary[1:], buffer: new(bytes.Buffer), } }
[ "func", "newBoundaryReader", "(", "reader", "*", "bufio", ".", "Reader", ",", "boundary", "string", ")", "*", "boundaryReader", "{", "fullBoundary", ":=", "[", "]", "byte", "(", "\"\\n--\"", "+", "\\n", "+", "boundary", ")", "\n", "\"--\"", "\n", "}" ]
// newBoundaryReader returns an initialized boundaryReader
[ "newBoundaryReader", "returns", "an", "initialized", "boundaryReader" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/boundary.go#L28-L37
test
jhillyerd/enmime
boundary.go
Read
func (b *boundaryReader) Read(dest []byte) (n int, err error) { if b.buffer.Len() >= len(dest) { // This read request can be satisfied entirely by the buffer return b.buffer.Read(dest) } peek, err := b.r.Peek(peekBufferSize) peekEOF := (err == io.EOF) if err != nil && !peekEOF && err != bufio.ErrBufferFull { // Unexpected error return 0, errors.WithStack(err) } var nCopy int idx, complete := locateBoundary(peek, b.nlPrefix) if idx != -1 { // Peeked boundary prefix, read until that point nCopy = idx if !complete && nCopy == 0 { // Incomplete boundary, move past it nCopy = 1 } } else { // No boundary found, move forward a safe distance if nCopy = len(peek) - len(b.nlPrefix) - 1; nCopy <= 0 { nCopy = 0 if peekEOF { // No more peek space remaining and no boundary found return 0, errors.WithStack(io.ErrUnexpectedEOF) } } } if nCopy > 0 { if _, err = io.CopyN(b.buffer, b.r, int64(nCopy)); err != nil { return 0, errors.WithStack(err) } } n, err = b.buffer.Read(dest) if err == io.EOF && !complete { // Only the buffer is empty, not the boundaryReader return n, nil } return n, err }
go
func (b *boundaryReader) Read(dest []byte) (n int, err error) { if b.buffer.Len() >= len(dest) { // This read request can be satisfied entirely by the buffer return b.buffer.Read(dest) } peek, err := b.r.Peek(peekBufferSize) peekEOF := (err == io.EOF) if err != nil && !peekEOF && err != bufio.ErrBufferFull { // Unexpected error return 0, errors.WithStack(err) } var nCopy int idx, complete := locateBoundary(peek, b.nlPrefix) if idx != -1 { // Peeked boundary prefix, read until that point nCopy = idx if !complete && nCopy == 0 { // Incomplete boundary, move past it nCopy = 1 } } else { // No boundary found, move forward a safe distance if nCopy = len(peek) - len(b.nlPrefix) - 1; nCopy <= 0 { nCopy = 0 if peekEOF { // No more peek space remaining and no boundary found return 0, errors.WithStack(io.ErrUnexpectedEOF) } } } if nCopy > 0 { if _, err = io.CopyN(b.buffer, b.r, int64(nCopy)); err != nil { return 0, errors.WithStack(err) } } n, err = b.buffer.Read(dest) if err == io.EOF && !complete { // Only the buffer is empty, not the boundaryReader return n, nil } return n, err }
[ "func", "(", "b", "*", "boundaryReader", ")", "Read", "(", "dest", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "b", ".", "buffer", ".", "Len", "(", ")", ">=", "len", "(", "dest", ")", "{", "return", "b", ".", "buffer", ".", "Read", "(", "dest", ")", "\n", "}", "\n", "peek", ",", "err", ":=", "b", ".", "r", ".", "Peek", "(", "peekBufferSize", ")", "\n", "peekEOF", ":=", "(", "err", "==", "io", ".", "EOF", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "peekEOF", "&&", "err", "!=", "bufio", ".", "ErrBufferFull", "{", "return", "0", ",", "errors", ".", "WithStack", "(", "err", ")", "\n", "}", "\n", "var", "nCopy", "int", "\n", "idx", ",", "complete", ":=", "locateBoundary", "(", "peek", ",", "b", ".", "nlPrefix", ")", "\n", "if", "idx", "!=", "-", "1", "{", "nCopy", "=", "idx", "\n", "if", "!", "complete", "&&", "nCopy", "==", "0", "{", "nCopy", "=", "1", "\n", "}", "\n", "}", "else", "{", "if", "nCopy", "=", "len", "(", "peek", ")", "-", "len", "(", "b", ".", "nlPrefix", ")", "-", "1", ";", "nCopy", "<=", "0", "{", "nCopy", "=", "0", "\n", "if", "peekEOF", "{", "return", "0", ",", "errors", ".", "WithStack", "(", "io", ".", "ErrUnexpectedEOF", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "nCopy", ">", "0", "{", "if", "_", ",", "err", "=", "io", ".", "CopyN", "(", "b", ".", "buffer", ",", "b", ".", "r", ",", "int64", "(", "nCopy", ")", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "WithStack", "(", "err", ")", "\n", "}", "\n", "}", "\n", "n", ",", "err", "=", "b", ".", "buffer", ".", "Read", "(", "dest", ")", "\n", "if", "err", "==", "io", ".", "EOF", "&&", "!", "complete", "{", "return", "n", ",", "nil", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Read returns a buffer containing the content up until boundary
[ "Read", "returns", "a", "buffer", "containing", "the", "content", "up", "until", "boundary" ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/boundary.go#L40-L83
test
jhillyerd/enmime
boundary.go
Next
func (b *boundaryReader) Next() (bool, error) { if b.finished { return false, nil } if b.partsRead > 0 { // Exhaust the current part to prevent errors when moving to the next part _, _ = io.Copy(ioutil.Discard, b) } for { line, err := b.r.ReadSlice('\n') if err != nil && err != io.EOF { return false, errors.WithStack(err) } if len(line) > 0 && (line[0] == '\r' || line[0] == '\n') { // Blank line continue } if b.isTerminator(line) { b.finished = true return false, nil } if err != io.EOF && b.isDelimiter(line) { // Start of a new part b.partsRead++ return true, nil } if err == io.EOF { // Intentionally not wrapping with stack return false, io.EOF } if b.partsRead == 0 { // The first part didn't find the starting delimiter, burn off any preamble in front of // the boundary continue } b.finished = true return false, errors.Errorf("expecting boundary %q, got %q", string(b.prefix), string(line)) } }
go
func (b *boundaryReader) Next() (bool, error) { if b.finished { return false, nil } if b.partsRead > 0 { // Exhaust the current part to prevent errors when moving to the next part _, _ = io.Copy(ioutil.Discard, b) } for { line, err := b.r.ReadSlice('\n') if err != nil && err != io.EOF { return false, errors.WithStack(err) } if len(line) > 0 && (line[0] == '\r' || line[0] == '\n') { // Blank line continue } if b.isTerminator(line) { b.finished = true return false, nil } if err != io.EOF && b.isDelimiter(line) { // Start of a new part b.partsRead++ return true, nil } if err == io.EOF { // Intentionally not wrapping with stack return false, io.EOF } if b.partsRead == 0 { // The first part didn't find the starting delimiter, burn off any preamble in front of // the boundary continue } b.finished = true return false, errors.Errorf("expecting boundary %q, got %q", string(b.prefix), string(line)) } }
[ "func", "(", "b", "*", "boundaryReader", ")", "Next", "(", ")", "(", "bool", ",", "error", ")", "{", "if", "b", ".", "finished", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "b", ".", "partsRead", ">", "0", "{", "_", ",", "_", "=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "b", ")", "\n", "}", "\n", "for", "{", "line", ",", "err", ":=", "b", ".", "r", ".", "ReadSlice", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "false", ",", "errors", ".", "WithStack", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "line", ")", ">", "0", "&&", "(", "line", "[", "0", "]", "==", "'\\r'", "||", "line", "[", "0", "]", "==", "'\\n'", ")", "{", "continue", "\n", "}", "\n", "if", "b", ".", "isTerminator", "(", "line", ")", "{", "b", ".", "finished", "=", "true", "\n", "return", "false", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "io", ".", "EOF", "&&", "b", ".", "isDelimiter", "(", "line", ")", "{", "b", ".", "partsRead", "++", "\n", "return", "true", ",", "nil", "\n", "}", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "false", ",", "io", ".", "EOF", "\n", "}", "\n", "if", "b", ".", "partsRead", "==", "0", "{", "continue", "\n", "}", "\n", "b", ".", "finished", "=", "true", "\n", "return", "false", ",", "errors", ".", "Errorf", "(", "\"expecting boundary %q, got %q\"", ",", "string", "(", "b", ".", "prefix", ")", ",", "string", "(", "line", ")", ")", "\n", "}", "\n", "}" ]
// Next moves over the boundary to the next part, returns true if there is another part to be read.
[ "Next", "moves", "over", "the", "boundary", "to", "the", "next", "part", "returns", "true", "if", "there", "is", "another", "part", "to", "be", "read", "." ]
874cc30e023f36bd1df525716196887b0f04851b
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/boundary.go#L86-L124
test
senseyeio/roger
sexp/factory.go
Parse
func Parse(buf []byte, offset int) (interface{}, error) { obj, _, err := parseReturningOffset(buf, offset) return obj, err }
go
func Parse(buf []byte, offset int) (interface{}, error) { obj, _, err := parseReturningOffset(buf, offset) return obj, err }
[ "func", "Parse", "(", "buf", "[", "]", "byte", ",", "offset", "int", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "obj", ",", "_", ",", "err", ":=", "parseReturningOffset", "(", "buf", ",", "offset", ")", "\n", "return", "obj", ",", "err", "\n", "}" ]
// Parse converts a byte array containing R SEXP to a golang object. // This can be converted to native golang types.
[ "Parse", "converts", "a", "byte", "array", "containing", "R", "SEXP", "to", "a", "golang", "object", ".", "This", "can", "be", "converted", "to", "native", "golang", "types", "." ]
5a944f2c5ceb5139f926c5ae134202ec2abba71a
https://github.com/senseyeio/roger/blob/5a944f2c5ceb5139f926c5ae134202ec2abba71a/sexp/factory.go#L15-L18
test
senseyeio/roger
assign/factory.go
Assign
func Assign(symbol string, value interface{}) ([]byte, error) { switch value.(type) { case []float64: return assignDoubleArray(symbol, value.([]float64)) case []int32: return assignIntArray(symbol, value.([]int32)) case []string: return assignStrArray(symbol, value.([]string)) case []byte: return assignByteArray(symbol, value.([]byte)) case string: return assignStr(symbol, value.(string)) case int32: return assignInt(symbol, value.(int32)) case float64: return assignDouble(symbol, value.(float64)) default: return nil, errors.New("session assign: type is not supported") } }
go
func Assign(symbol string, value interface{}) ([]byte, error) { switch value.(type) { case []float64: return assignDoubleArray(symbol, value.([]float64)) case []int32: return assignIntArray(symbol, value.([]int32)) case []string: return assignStrArray(symbol, value.([]string)) case []byte: return assignByteArray(symbol, value.([]byte)) case string: return assignStr(symbol, value.(string)) case int32: return assignInt(symbol, value.(int32)) case float64: return assignDouble(symbol, value.(float64)) default: return nil, errors.New("session assign: type is not supported") } }
[ "func", "Assign", "(", "symbol", "string", ",", "value", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "switch", "value", ".", "(", "type", ")", "{", "case", "[", "]", "float64", ":", "return", "assignDoubleArray", "(", "symbol", ",", "value", ".", "(", "[", "]", "float64", ")", ")", "\n", "case", "[", "]", "int32", ":", "return", "assignIntArray", "(", "symbol", ",", "value", ".", "(", "[", "]", "int32", ")", ")", "\n", "case", "[", "]", "string", ":", "return", "assignStrArray", "(", "symbol", ",", "value", ".", "(", "[", "]", "string", ")", ")", "\n", "case", "[", "]", "byte", ":", "return", "assignByteArray", "(", "symbol", ",", "value", ".", "(", "[", "]", "byte", ")", ")", "\n", "case", "string", ":", "return", "assignStr", "(", "symbol", ",", "value", ".", "(", "string", ")", ")", "\n", "case", "int32", ":", "return", "assignInt", "(", "symbol", ",", "value", ".", "(", "int32", ")", ")", "\n", "case", "float64", ":", "return", "assignDouble", "(", "symbol", ",", "value", ".", "(", "float64", ")", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"session assign: type is not supported\"", ")", "\n", "}", "\n", "}" ]
// Assign produces a command to assign a value to a variable within a go session
[ "Assign", "produces", "a", "command", "to", "assign", "a", "value", "to", "a", "variable", "within", "a", "go", "session" ]
5a944f2c5ceb5139f926c5ae134202ec2abba71a
https://github.com/senseyeio/roger/blob/5a944f2c5ceb5139f926c5ae134202ec2abba71a/assign/factory.go#L6-L25
test
senseyeio/roger
client.go
NewRClient
func NewRClient(host string, port int64) (RClient, error) { return NewRClientWithAuth(host, port, "", "") }
go
func NewRClient(host string, port int64) (RClient, error) { return NewRClientWithAuth(host, port, "", "") }
[ "func", "NewRClient", "(", "host", "string", ",", "port", "int64", ")", "(", "RClient", ",", "error", ")", "{", "return", "NewRClientWithAuth", "(", "host", ",", "port", ",", "\"\"", ",", "\"\"", ")", "\n", "}" ]
// NewRClient creates a RClient which will run commands on the RServe server located at the provided host and port
[ "NewRClient", "creates", "a", "RClient", "which", "will", "run", "commands", "on", "the", "RServe", "server", "located", "at", "the", "provided", "host", "and", "port" ]
5a944f2c5ceb5139f926c5ae134202ec2abba71a
https://github.com/senseyeio/roger/blob/5a944f2c5ceb5139f926c5ae134202ec2abba71a/client.go#L32-L34
test
senseyeio/roger
client.go
NewRClientWithAuth
func NewRClientWithAuth(host string, port int64, user, password string) (RClient, error) { addr, err := net.ResolveTCPAddr("tcp", host+":"+strconv.FormatInt(port, 10)) if err != nil { return nil, err } rClient := &roger{ address: addr, user: user, password: password, } if _, err = rClient.Eval("'Test session connection'"); err != nil { return nil, err } return rClient, nil }
go
func NewRClientWithAuth(host string, port int64, user, password string) (RClient, error) { addr, err := net.ResolveTCPAddr("tcp", host+":"+strconv.FormatInt(port, 10)) if err != nil { return nil, err } rClient := &roger{ address: addr, user: user, password: password, } if _, err = rClient.Eval("'Test session connection'"); err != nil { return nil, err } return rClient, nil }
[ "func", "NewRClientWithAuth", "(", "host", "string", ",", "port", "int64", ",", "user", ",", "password", "string", ")", "(", "RClient", ",", "error", ")", "{", "addr", ",", "err", ":=", "net", ".", "ResolveTCPAddr", "(", "\"tcp\"", ",", "host", "+", "\":\"", "+", "strconv", ".", "FormatInt", "(", "port", ",", "10", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "rClient", ":=", "&", "roger", "{", "address", ":", "addr", ",", "user", ":", "user", ",", "password", ":", "password", ",", "}", "\n", "if", "_", ",", "err", "=", "rClient", ".", "Eval", "(", "\"'Test session connection'\"", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "rClient", ",", "nil", "\n", "}" ]
// NewRClientWithAuth creates a RClient with the specified credentials and RServe server details
[ "NewRClientWithAuth", "creates", "a", "RClient", "with", "the", "specified", "credentials", "and", "RServe", "server", "details" ]
5a944f2c5ceb5139f926c5ae134202ec2abba71a
https://github.com/senseyeio/roger/blob/5a944f2c5ceb5139f926c5ae134202ec2abba71a/client.go#L37-L53
test
wawandco/fako
fakers.go
Register
func Register(identifier string, generator func() string) { fakeType := inflect.Camelize(identifier) customGenerators[fakeType] = generator }
go
func Register(identifier string, generator func() string) { fakeType := inflect.Camelize(identifier) customGenerators[fakeType] = generator }
[ "func", "Register", "(", "identifier", "string", ",", "generator", "func", "(", ")", "string", ")", "{", "fakeType", ":=", "inflect", ".", "Camelize", "(", "identifier", ")", "\n", "customGenerators", "[", "fakeType", "]", "=", "generator", "\n", "}" ]
// Register allows user to add his own data generators for special cases // that we could not cover with the generators that fako includes by default.
[ "Register", "allows", "user", "to", "add", "his", "own", "data", "generators", "for", "special", "cases", "that", "we", "could", "not", "cover", "with", "the", "generators", "that", "fako", "includes", "by", "default", "." ]
c36a0bc97398c9100daa83ebef1c4e7af32c7654
https://github.com/wawandco/fako/blob/c36a0bc97398c9100daa83ebef1c4e7af32c7654/fakers.go#L86-L89
test
wawandco/fako
fakers.go
Fuzz
func Fuzz(e interface{}) { ty := reflect.TypeOf(e) if ty.Kind() == reflect.Ptr { ty = ty.Elem() } if ty.Kind() == reflect.Struct { value := reflect.ValueOf(e).Elem() for i := 0; i < ty.NumField(); i++ { field := value.Field(i) if field.CanSet() { field.Set(fuzzValueFor(field.Kind())) } } } }
go
func Fuzz(e interface{}) { ty := reflect.TypeOf(e) if ty.Kind() == reflect.Ptr { ty = ty.Elem() } if ty.Kind() == reflect.Struct { value := reflect.ValueOf(e).Elem() for i := 0; i < ty.NumField(); i++ { field := value.Field(i) if field.CanSet() { field.Set(fuzzValueFor(field.Kind())) } } } }
[ "func", "Fuzz", "(", "e", "interface", "{", "}", ")", "{", "ty", ":=", "reflect", ".", "TypeOf", "(", "e", ")", "\n", "if", "ty", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "ty", "=", "ty", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "ty", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "{", "value", ":=", "reflect", ".", "ValueOf", "(", "e", ")", ".", "Elem", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "ty", ".", "NumField", "(", ")", ";", "i", "++", "{", "field", ":=", "value", ".", "Field", "(", "i", ")", "\n", "if", "field", ".", "CanSet", "(", ")", "{", "field", ".", "Set", "(", "fuzzValueFor", "(", "field", ".", "Kind", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Fuzz Fills passed interface with random data based on the struct field type, // take a look at fuzzValueFor for details on supported data types.
[ "Fuzz", "Fills", "passed", "interface", "with", "random", "data", "based", "on", "the", "struct", "field", "type", "take", "a", "look", "at", "fuzzValueFor", "for", "details", "on", "supported", "data", "types", "." ]
c36a0bc97398c9100daa83ebef1c4e7af32c7654
https://github.com/wawandco/fako/blob/c36a0bc97398c9100daa83ebef1c4e7af32c7654/fakers.go#L93-L111
test
wawandco/fako
fakers.go
findFakeFunctionFor
func findFakeFunctionFor(fako string) func() string { result := func() string { return "" } for kind, function := range allGenerators() { if fako == kind { result = function break } } return result }
go
func findFakeFunctionFor(fako string) func() string { result := func() string { return "" } for kind, function := range allGenerators() { if fako == kind { result = function break } } return result }
[ "func", "findFakeFunctionFor", "(", "fako", "string", ")", "func", "(", ")", "string", "{", "result", ":=", "func", "(", ")", "string", "{", "return", "\"\"", "}", "\n", "for", "kind", ",", "function", ":=", "range", "allGenerators", "(", ")", "{", "if", "fako", "==", "kind", "{", "result", "=", "function", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
//findFakeFunctionFor returns a faker function for a fako identifier
[ "findFakeFunctionFor", "returns", "a", "faker", "function", "for", "a", "fako", "identifier" ]
c36a0bc97398c9100daa83ebef1c4e7af32c7654
https://github.com/wawandco/fako/blob/c36a0bc97398c9100daa83ebef1c4e7af32c7654/fakers.go#L123-L134
test
libp2p/go-libp2p-routing
options/options.go
Apply
func (opts *Options) Apply(options ...Option) error { for _, o := range options { if err := o(opts); err != nil { return err } } return nil }
go
func (opts *Options) Apply(options ...Option) error { for _, o := range options { if err := o(opts); err != nil { return err } } return nil }
[ "func", "(", "opts", "*", "Options", ")", "Apply", "(", "options", "...", "Option", ")", "error", "{", "for", "_", ",", "o", ":=", "range", "options", "{", "if", "err", ":=", "o", "(", "opts", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Apply applies the given options to this Options
[ "Apply", "applies", "the", "given", "options", "to", "this", "Options" ]
15c28e7faa25921fd1160412003fecdc70e09a5c
https://github.com/libp2p/go-libp2p-routing/blob/15c28e7faa25921fd1160412003fecdc70e09a5c/options/options.go#L16-L23
test
libp2p/go-libp2p-routing
options/options.go
ToOption
func (opts *Options) ToOption() Option { return func(nopts *Options) error { *nopts = *opts if opts.Other != nil { nopts.Other = make(map[interface{}]interface{}, len(opts.Other)) for k, v := range opts.Other { nopts.Other[k] = v } } return nil } }
go
func (opts *Options) ToOption() Option { return func(nopts *Options) error { *nopts = *opts if opts.Other != nil { nopts.Other = make(map[interface{}]interface{}, len(opts.Other)) for k, v := range opts.Other { nopts.Other[k] = v } } return nil } }
[ "func", "(", "opts", "*", "Options", ")", "ToOption", "(", ")", "Option", "{", "return", "func", "(", "nopts", "*", "Options", ")", "error", "{", "*", "nopts", "=", "*", "opts", "\n", "if", "opts", ".", "Other", "!=", "nil", "{", "nopts", ".", "Other", "=", "make", "(", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", ",", "len", "(", "opts", ".", "Other", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "opts", ".", "Other", "{", "nopts", ".", "Other", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ToOption converts this Options to a single Option.
[ "ToOption", "converts", "this", "Options", "to", "a", "single", "Option", "." ]
15c28e7faa25921fd1160412003fecdc70e09a5c
https://github.com/libp2p/go-libp2p-routing/blob/15c28e7faa25921fd1160412003fecdc70e09a5c/options/options.go#L26-L37
test
libp2p/go-libp2p-routing
notifications/query.go
waitThenClose
func (e *eventChannel) waitThenClose() { <-e.ctx.Done() e.mu.Lock() close(e.ch) // 1. Signals that we're done. // 2. Frees memory (in case we end up hanging on to this for a while). e.ch = nil e.mu.Unlock() }
go
func (e *eventChannel) waitThenClose() { <-e.ctx.Done() e.mu.Lock() close(e.ch) // 1. Signals that we're done. // 2. Frees memory (in case we end up hanging on to this for a while). e.ch = nil e.mu.Unlock() }
[ "func", "(", "e", "*", "eventChannel", ")", "waitThenClose", "(", ")", "{", "<-", "e", ".", "ctx", ".", "Done", "(", ")", "\n", "e", ".", "mu", ".", "Lock", "(", ")", "\n", "close", "(", "e", ".", "ch", ")", "\n", "e", ".", "ch", "=", "nil", "\n", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// waitThenClose is spawned in a goroutine when the channel is registered. This // safely cleans up the channel when the context has been canceled.
[ "waitThenClose", "is", "spawned", "in", "a", "goroutine", "when", "the", "channel", "is", "registered", ".", "This", "safely", "cleans", "up", "the", "channel", "when", "the", "context", "has", "been", "canceled", "." ]
15c28e7faa25921fd1160412003fecdc70e09a5c
https://github.com/libp2p/go-libp2p-routing/blob/15c28e7faa25921fd1160412003fecdc70e09a5c/notifications/query.go#L44-L52
test
libp2p/go-libp2p-routing
notifications/query.go
send
func (e *eventChannel) send(ctx context.Context, ev *QueryEvent) { e.mu.Lock() // Closed. if e.ch == nil { e.mu.Unlock() return } // in case the passed context is unrelated, wait on both. select { case e.ch <- ev: case <-e.ctx.Done(): case <-ctx.Done(): } e.mu.Unlock() }
go
func (e *eventChannel) send(ctx context.Context, ev *QueryEvent) { e.mu.Lock() // Closed. if e.ch == nil { e.mu.Unlock() return } // in case the passed context is unrelated, wait on both. select { case e.ch <- ev: case <-e.ctx.Done(): case <-ctx.Done(): } e.mu.Unlock() }
[ "func", "(", "e", "*", "eventChannel", ")", "send", "(", "ctx", "context", ".", "Context", ",", "ev", "*", "QueryEvent", ")", "{", "e", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "e", ".", "ch", "==", "nil", "{", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "select", "{", "case", "e", ".", "ch", "<-", "ev", ":", "case", "<-", "e", ".", "ctx", ".", "Done", "(", ")", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "}", "\n", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// send sends an event on the event channel, aborting if either the passed or // the internal context expire.
[ "send", "sends", "an", "event", "on", "the", "event", "channel", "aborting", "if", "either", "the", "passed", "or", "the", "internal", "context", "expire", "." ]
15c28e7faa25921fd1160412003fecdc70e09a5c
https://github.com/libp2p/go-libp2p-routing/blob/15c28e7faa25921fd1160412003fecdc70e09a5c/notifications/query.go#L56-L70
test
VividCortex/ewma
ewma.go
NewMovingAverage
func NewMovingAverage(age ...float64) MovingAverage { if len(age) == 0 || age[0] == AVG_METRIC_AGE { return new(SimpleEWMA) } return &VariableEWMA{ decay: 2 / (age[0] + 1), } }
go
func NewMovingAverage(age ...float64) MovingAverage { if len(age) == 0 || age[0] == AVG_METRIC_AGE { return new(SimpleEWMA) } return &VariableEWMA{ decay: 2 / (age[0] + 1), } }
[ "func", "NewMovingAverage", "(", "age", "...", "float64", ")", "MovingAverage", "{", "if", "len", "(", "age", ")", "==", "0", "||", "age", "[", "0", "]", "==", "AVG_METRIC_AGE", "{", "return", "new", "(", "SimpleEWMA", ")", "\n", "}", "\n", "return", "&", "VariableEWMA", "{", "decay", ":", "2", "/", "(", "age", "[", "0", "]", "+", "1", ")", ",", "}", "\n", "}" ]
// NewMovingAverage constructs a MovingAverage that computes an average with the // desired characteristics in the moving window or exponential decay. If no // age is given, it constructs a default exponentially weighted implementation // that consumes minimal memory. The age is related to the decay factor alpha // by the formula given for the DECAY constant. It signifies the average age // of the samples as time goes to infinity.
[ "NewMovingAverage", "constructs", "a", "MovingAverage", "that", "computes", "an", "average", "with", "the", "desired", "characteristics", "in", "the", "moving", "window", "or", "exponential", "decay", ".", "If", "no", "age", "is", "given", "it", "constructs", "a", "default", "exponentially", "weighted", "implementation", "that", "consumes", "minimal", "memory", ".", "The", "age", "is", "related", "to", "the", "decay", "factor", "alpha", "by", "the", "formula", "given", "for", "the", "DECAY", "constant", ".", "It", "signifies", "the", "average", "age", "of", "the", "samples", "as", "time", "goes", "to", "infinity", "." ]
43880d236f695d39c62cf7aa4ebd4508c258e6c0
https://github.com/VividCortex/ewma/blob/43880d236f695d39c62cf7aa4ebd4508c258e6c0/ewma.go#L40-L47
test
VividCortex/ewma
ewma.go
Set
func (e *VariableEWMA) Set(value float64) { e.value = value if e.count <= WARMUP_SAMPLES { e.count = WARMUP_SAMPLES + 1 } }
go
func (e *VariableEWMA) Set(value float64) { e.value = value if e.count <= WARMUP_SAMPLES { e.count = WARMUP_SAMPLES + 1 } }
[ "func", "(", "e", "*", "VariableEWMA", ")", "Set", "(", "value", "float64", ")", "{", "e", ".", "value", "=", "value", "\n", "if", "e", ".", "count", "<=", "WARMUP_SAMPLES", "{", "e", ".", "count", "=", "WARMUP_SAMPLES", "+", "1", "\n", "}", "\n", "}" ]
// Set sets the EWMA's value.
[ "Set", "sets", "the", "EWMA", "s", "value", "." ]
43880d236f695d39c62cf7aa4ebd4508c258e6c0
https://github.com/VividCortex/ewma/blob/43880d236f695d39c62cf7aa4ebd4508c258e6c0/ewma.go#L121-L126
test
nwaples/rardecode
archive50.go
calcKeys50
func calcKeys50(pass, salt []byte, kdfCount int) [][]byte { if len(salt) > maxPbkdf2Salt { salt = salt[:maxPbkdf2Salt] } keys := make([][]byte, 3) if len(keys) == 0 { return keys } prf := hmac.New(sha256.New, pass) prf.Write(salt) prf.Write([]byte{0, 0, 0, 1}) t := prf.Sum(nil) u := append([]byte(nil), t...) kdfCount-- for i, iter := range []int{kdfCount, 16, 16} { for iter > 0 { prf.Reset() prf.Write(u) u = prf.Sum(u[:0]) for j := range u { t[j] ^= u[j] } iter-- } keys[i] = append([]byte(nil), t...) } pwcheck := keys[2] for i, v := range pwcheck[pwCheckSize:] { pwcheck[i&(pwCheckSize-1)] ^= v } keys[2] = pwcheck[:pwCheckSize] return keys }
go
func calcKeys50(pass, salt []byte, kdfCount int) [][]byte { if len(salt) > maxPbkdf2Salt { salt = salt[:maxPbkdf2Salt] } keys := make([][]byte, 3) if len(keys) == 0 { return keys } prf := hmac.New(sha256.New, pass) prf.Write(salt) prf.Write([]byte{0, 0, 0, 1}) t := prf.Sum(nil) u := append([]byte(nil), t...) kdfCount-- for i, iter := range []int{kdfCount, 16, 16} { for iter > 0 { prf.Reset() prf.Write(u) u = prf.Sum(u[:0]) for j := range u { t[j] ^= u[j] } iter-- } keys[i] = append([]byte(nil), t...) } pwcheck := keys[2] for i, v := range pwcheck[pwCheckSize:] { pwcheck[i&(pwCheckSize-1)] ^= v } keys[2] = pwcheck[:pwCheckSize] return keys }
[ "func", "calcKeys50", "(", "pass", ",", "salt", "[", "]", "byte", ",", "kdfCount", "int", ")", "[", "]", "[", "]", "byte", "{", "if", "len", "(", "salt", ")", ">", "maxPbkdf2Salt", "{", "salt", "=", "salt", "[", ":", "maxPbkdf2Salt", "]", "\n", "}", "\n", "keys", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "3", ")", "\n", "if", "len", "(", "keys", ")", "==", "0", "{", "return", "keys", "\n", "}", "\n", "prf", ":=", "hmac", ".", "New", "(", "sha256", ".", "New", ",", "pass", ")", "\n", "prf", ".", "Write", "(", "salt", ")", "\n", "prf", ".", "Write", "(", "[", "]", "byte", "{", "0", ",", "0", ",", "0", ",", "1", "}", ")", "\n", "t", ":=", "prf", ".", "Sum", "(", "nil", ")", "\n", "u", ":=", "append", "(", "[", "]", "byte", "(", "nil", ")", ",", "t", "...", ")", "\n", "kdfCount", "--", "\n", "for", "i", ",", "iter", ":=", "range", "[", "]", "int", "{", "kdfCount", ",", "16", ",", "16", "}", "{", "for", "iter", ">", "0", "{", "prf", ".", "Reset", "(", ")", "\n", "prf", ".", "Write", "(", "u", ")", "\n", "u", "=", "prf", ".", "Sum", "(", "u", "[", ":", "0", "]", ")", "\n", "for", "j", ":=", "range", "u", "{", "t", "[", "j", "]", "^=", "u", "[", "j", "]", "\n", "}", "\n", "iter", "--", "\n", "}", "\n", "keys", "[", "i", "]", "=", "append", "(", "[", "]", "byte", "(", "nil", ")", ",", "t", "...", ")", "\n", "}", "\n", "pwcheck", ":=", "keys", "[", "2", "]", "\n", "for", "i", ",", "v", ":=", "range", "pwcheck", "[", "pwCheckSize", ":", "]", "{", "pwcheck", "[", "i", "&", "(", "pwCheckSize", "-", "1", ")", "]", "^=", "v", "\n", "}", "\n", "keys", "[", "2", "]", "=", "pwcheck", "[", ":", "pwCheckSize", "]", "\n", "return", "keys", "\n", "}" ]
// calcKeys50 calculates the keys used in RAR 5 archive processing. // The returned slice of byte slices contains 3 keys. // Key 0 is used for block or file decryption. // Key 1 is optionally used for file checksum calculation. // Key 2 is optionally used for password checking.
[ "calcKeys50", "calculates", "the", "keys", "used", "in", "RAR", "5", "archive", "processing", ".", "The", "returned", "slice", "of", "byte", "slices", "contains", "3", "keys", ".", "Key", "0", "is", "used", "for", "block", "or", "file", "decryption", ".", "Key", "1", "is", "optionally", "used", "for", "file", "checksum", "calculation", ".", "Key", "2", "is", "optionally", "used", "for", "password", "checking", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L139-L177
test
nwaples/rardecode
archive50.go
getKeys
func (a *archive50) getKeys(b *readBuf) (keys [][]byte, err error) { if len(*b) < 17 { return nil, errCorruptEncrypt } // read kdf count and salt kdfCount := int(b.byte()) if kdfCount > maxKdfCount { return nil, errCorruptEncrypt } kdfCount = 1 << uint(kdfCount) salt := b.bytes(16) // check cache of keys for match for _, v := range a.keyCache { if kdfCount == v.kdfCount && bytes.Equal(salt, v.salt) { return v.keys, nil } } // not found, calculate keys keys = calcKeys50(a.pass, salt, kdfCount) // store in cache copy(a.keyCache[1:], a.keyCache[:]) a.keyCache[0].kdfCount = kdfCount a.keyCache[0].salt = append([]byte(nil), salt...) a.keyCache[0].keys = keys return keys, nil }
go
func (a *archive50) getKeys(b *readBuf) (keys [][]byte, err error) { if len(*b) < 17 { return nil, errCorruptEncrypt } // read kdf count and salt kdfCount := int(b.byte()) if kdfCount > maxKdfCount { return nil, errCorruptEncrypt } kdfCount = 1 << uint(kdfCount) salt := b.bytes(16) // check cache of keys for match for _, v := range a.keyCache { if kdfCount == v.kdfCount && bytes.Equal(salt, v.salt) { return v.keys, nil } } // not found, calculate keys keys = calcKeys50(a.pass, salt, kdfCount) // store in cache copy(a.keyCache[1:], a.keyCache[:]) a.keyCache[0].kdfCount = kdfCount a.keyCache[0].salt = append([]byte(nil), salt...) a.keyCache[0].keys = keys return keys, nil }
[ "func", "(", "a", "*", "archive50", ")", "getKeys", "(", "b", "*", "readBuf", ")", "(", "keys", "[", "]", "[", "]", "byte", ",", "err", "error", ")", "{", "if", "len", "(", "*", "b", ")", "<", "17", "{", "return", "nil", ",", "errCorruptEncrypt", "\n", "}", "\n", "kdfCount", ":=", "int", "(", "b", ".", "byte", "(", ")", ")", "\n", "if", "kdfCount", ">", "maxKdfCount", "{", "return", "nil", ",", "errCorruptEncrypt", "\n", "}", "\n", "kdfCount", "=", "1", "<<", "uint", "(", "kdfCount", ")", "\n", "salt", ":=", "b", ".", "bytes", "(", "16", ")", "\n", "for", "_", ",", "v", ":=", "range", "a", ".", "keyCache", "{", "if", "kdfCount", "==", "v", ".", "kdfCount", "&&", "bytes", ".", "Equal", "(", "salt", ",", "v", ".", "salt", ")", "{", "return", "v", ".", "keys", ",", "nil", "\n", "}", "\n", "}", "\n", "keys", "=", "calcKeys50", "(", "a", ".", "pass", ",", "salt", ",", "kdfCount", ")", "\n", "copy", "(", "a", ".", "keyCache", "[", "1", ":", "]", ",", "a", ".", "keyCache", "[", ":", "]", ")", "\n", "a", ".", "keyCache", "[", "0", "]", ".", "kdfCount", "=", "kdfCount", "\n", "a", ".", "keyCache", "[", "0", "]", ".", "salt", "=", "append", "(", "[", "]", "byte", "(", "nil", ")", ",", "salt", "...", ")", "\n", "a", ".", "keyCache", "[", "0", "]", ".", "keys", "=", "keys", "\n", "return", "keys", ",", "nil", "\n", "}" ]
// getKeys reads kdfcount and salt from b and returns the corresponding encryption keys.
[ "getKeys", "reads", "kdfcount", "and", "salt", "from", "b", "and", "returns", "the", "corresponding", "encryption", "keys", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L180-L208
test
nwaples/rardecode
archive50.go
checkPassword
func checkPassword(b *readBuf, keys [][]byte) error { if len(*b) < 12 { return nil // not enough bytes, ignore for the moment } pwcheck := b.bytes(8) sum := b.bytes(4) csum := sha256.Sum256(pwcheck) if bytes.Equal(sum, csum[:len(sum)]) && !bytes.Equal(pwcheck, keys[2]) { return errBadPassword } return nil }
go
func checkPassword(b *readBuf, keys [][]byte) error { if len(*b) < 12 { return nil // not enough bytes, ignore for the moment } pwcheck := b.bytes(8) sum := b.bytes(4) csum := sha256.Sum256(pwcheck) if bytes.Equal(sum, csum[:len(sum)]) && !bytes.Equal(pwcheck, keys[2]) { return errBadPassword } return nil }
[ "func", "checkPassword", "(", "b", "*", "readBuf", ",", "keys", "[", "]", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "*", "b", ")", "<", "12", "{", "return", "nil", "\n", "}", "\n", "pwcheck", ":=", "b", ".", "bytes", "(", "8", ")", "\n", "sum", ":=", "b", ".", "bytes", "(", "4", ")", "\n", "csum", ":=", "sha256", ".", "Sum256", "(", "pwcheck", ")", "\n", "if", "bytes", ".", "Equal", "(", "sum", ",", "csum", "[", ":", "len", "(", "sum", ")", "]", ")", "&&", "!", "bytes", ".", "Equal", "(", "pwcheck", ",", "keys", "[", "2", "]", ")", "{", "return", "errBadPassword", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkPassword calculates if a password is correct given password check data and keys.
[ "checkPassword", "calculates", "if", "a", "password", "is", "correct", "given", "password", "check", "data", "and", "keys", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L211-L222
test
nwaples/rardecode
archive50.go
parseFileEncryptionRecord
func (a *archive50) parseFileEncryptionRecord(b readBuf, f *fileBlockHeader) error { if ver := b.uvarint(); ver != 0 { return errUnknownEncMethod } flags := b.uvarint() keys, err := a.getKeys(&b) if err != nil { return err } f.key = keys[0] if len(b) < 16 { return errCorruptEncrypt } f.iv = b.bytes(16) if flags&file5EncCheckPresent > 0 { if err := checkPassword(&b, keys); err != nil { return err } } if flags&file5EncUseMac > 0 { a.checksum.key = keys[1] } return nil }
go
func (a *archive50) parseFileEncryptionRecord(b readBuf, f *fileBlockHeader) error { if ver := b.uvarint(); ver != 0 { return errUnknownEncMethod } flags := b.uvarint() keys, err := a.getKeys(&b) if err != nil { return err } f.key = keys[0] if len(b) < 16 { return errCorruptEncrypt } f.iv = b.bytes(16) if flags&file5EncCheckPresent > 0 { if err := checkPassword(&b, keys); err != nil { return err } } if flags&file5EncUseMac > 0 { a.checksum.key = keys[1] } return nil }
[ "func", "(", "a", "*", "archive50", ")", "parseFileEncryptionRecord", "(", "b", "readBuf", ",", "f", "*", "fileBlockHeader", ")", "error", "{", "if", "ver", ":=", "b", ".", "uvarint", "(", ")", ";", "ver", "!=", "0", "{", "return", "errUnknownEncMethod", "\n", "}", "\n", "flags", ":=", "b", ".", "uvarint", "(", ")", "\n", "keys", ",", "err", ":=", "a", ".", "getKeys", "(", "&", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "key", "=", "keys", "[", "0", "]", "\n", "if", "len", "(", "b", ")", "<", "16", "{", "return", "errCorruptEncrypt", "\n", "}", "\n", "f", ".", "iv", "=", "b", ".", "bytes", "(", "16", ")", "\n", "if", "flags", "&", "file5EncCheckPresent", ">", "0", "{", "if", "err", ":=", "checkPassword", "(", "&", "b", ",", "keys", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "flags", "&", "file5EncUseMac", ">", "0", "{", "a", ".", "checksum", ".", "key", "=", "keys", "[", "1", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// parseFileEncryptionRecord processes the optional file encryption record from a file header.
[ "parseFileEncryptionRecord", "processes", "the", "optional", "file", "encryption", "record", "from", "a", "file", "header", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L225-L251
test
nwaples/rardecode
archive50.go
parseEncryptionBlock
func (a *archive50) parseEncryptionBlock(b readBuf) error { if ver := b.uvarint(); ver != 0 { return errUnknownEncMethod } flags := b.uvarint() keys, err := a.getKeys(&b) if err != nil { return err } if flags&enc5CheckPresent > 0 { if err := checkPassword(&b, keys); err != nil { return err } } a.blockKey = keys[0] return nil }
go
func (a *archive50) parseEncryptionBlock(b readBuf) error { if ver := b.uvarint(); ver != 0 { return errUnknownEncMethod } flags := b.uvarint() keys, err := a.getKeys(&b) if err != nil { return err } if flags&enc5CheckPresent > 0 { if err := checkPassword(&b, keys); err != nil { return err } } a.blockKey = keys[0] return nil }
[ "func", "(", "a", "*", "archive50", ")", "parseEncryptionBlock", "(", "b", "readBuf", ")", "error", "{", "if", "ver", ":=", "b", ".", "uvarint", "(", ")", ";", "ver", "!=", "0", "{", "return", "errUnknownEncMethod", "\n", "}", "\n", "flags", ":=", "b", ".", "uvarint", "(", ")", "\n", "keys", ",", "err", ":=", "a", ".", "getKeys", "(", "&", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "flags", "&", "enc5CheckPresent", ">", "0", "{", "if", "err", ":=", "checkPassword", "(", "&", "b", ",", "keys", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "a", ".", "blockKey", "=", "keys", "[", "0", "]", "\n", "return", "nil", "\n", "}" ]
// parseEncryptionBlock calculates the key for block encryption.
[ "parseEncryptionBlock", "calculates", "the", "key", "for", "block", "encryption", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L339-L355
test
nwaples/rardecode
archive50.go
newArchive50
func newArchive50(r *bufio.Reader, password string) fileBlockReader { a := new(archive50) a.v = r a.pass = []byte(password) a.buf = make([]byte, 100) return a }
go
func newArchive50(r *bufio.Reader, password string) fileBlockReader { a := new(archive50) a.v = r a.pass = []byte(password) a.buf = make([]byte, 100) return a }
[ "func", "newArchive50", "(", "r", "*", "bufio", ".", "Reader", ",", "password", "string", ")", "fileBlockReader", "{", "a", ":=", "new", "(", "archive50", ")", "\n", "a", ".", "v", "=", "r", "\n", "a", ".", "pass", "=", "[", "]", "byte", "(", "password", ")", "\n", "a", ".", "buf", "=", "make", "(", "[", "]", "byte", ",", "100", ")", "\n", "return", "a", "\n", "}" ]
// newArchive50 creates a new fileBlockReader for a Version 5 archive.
[ "newArchive50", "creates", "a", "new", "fileBlockReader", "for", "a", "Version", "5", "archive", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L469-L475
test
nwaples/rardecode
decrypt_reader.go
Read
func (cr *cipherBlockReader) Read(p []byte) (n int, err error) { for { if cr.n < len(cr.outbuf) { // return buffered output n = copy(p, cr.outbuf[cr.n:]) cr.n += n return n, nil } if cr.err != nil { err = cr.err cr.err = nil return 0, err } if len(p) >= cap(cr.outbuf) { break } // p is not large enough to process a block, use outbuf instead n, cr.err = cr.read(cr.outbuf[:cap(cr.outbuf)]) cr.outbuf = cr.outbuf[:n] cr.n = 0 } // read blocks into p return cr.read(p) }
go
func (cr *cipherBlockReader) Read(p []byte) (n int, err error) { for { if cr.n < len(cr.outbuf) { // return buffered output n = copy(p, cr.outbuf[cr.n:]) cr.n += n return n, nil } if cr.err != nil { err = cr.err cr.err = nil return 0, err } if len(p) >= cap(cr.outbuf) { break } // p is not large enough to process a block, use outbuf instead n, cr.err = cr.read(cr.outbuf[:cap(cr.outbuf)]) cr.outbuf = cr.outbuf[:n] cr.n = 0 } // read blocks into p return cr.read(p) }
[ "func", "(", "cr", "*", "cipherBlockReader", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "for", "{", "if", "cr", ".", "n", "<", "len", "(", "cr", ".", "outbuf", ")", "{", "n", "=", "copy", "(", "p", ",", "cr", ".", "outbuf", "[", "cr", ".", "n", ":", "]", ")", "\n", "cr", ".", "n", "+=", "n", "\n", "return", "n", ",", "nil", "\n", "}", "\n", "if", "cr", ".", "err", "!=", "nil", "{", "err", "=", "cr", ".", "err", "\n", "cr", ".", "err", "=", "nil", "\n", "return", "0", ",", "err", "\n", "}", "\n", "if", "len", "(", "p", ")", ">=", "cap", "(", "cr", ".", "outbuf", ")", "{", "break", "\n", "}", "\n", "n", ",", "cr", ".", "err", "=", "cr", ".", "read", "(", "cr", ".", "outbuf", "[", ":", "cap", "(", "cr", ".", "outbuf", ")", "]", ")", "\n", "cr", ".", "outbuf", "=", "cr", ".", "outbuf", "[", ":", "n", "]", "\n", "cr", ".", "n", "=", "0", "\n", "}", "\n", "return", "cr", ".", "read", "(", "p", ")", "\n", "}" ]
// Read reads and decrypts data into p. // If the input is not a multiple of the cipher block size, // the trailing bytes will be ignored.
[ "Read", "reads", "and", "decrypts", "data", "into", "p", ".", "If", "the", "input", "is", "not", "a", "multiple", "of", "the", "cipher", "block", "size", "the", "trailing", "bytes", "will", "be", "ignored", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decrypt_reader.go#L61-L84
test
nwaples/rardecode
decrypt_reader.go
ReadByte
func (cr *cipherBlockReader) ReadByte() (byte, error) { for { if cr.n < len(cr.outbuf) { c := cr.outbuf[cr.n] cr.n++ return c, nil } if cr.err != nil { err := cr.err cr.err = nil return 0, err } // refill outbuf var n int n, cr.err = cr.read(cr.outbuf[:cap(cr.outbuf)]) cr.outbuf = cr.outbuf[:n] cr.n = 0 } }
go
func (cr *cipherBlockReader) ReadByte() (byte, error) { for { if cr.n < len(cr.outbuf) { c := cr.outbuf[cr.n] cr.n++ return c, nil } if cr.err != nil { err := cr.err cr.err = nil return 0, err } // refill outbuf var n int n, cr.err = cr.read(cr.outbuf[:cap(cr.outbuf)]) cr.outbuf = cr.outbuf[:n] cr.n = 0 } }
[ "func", "(", "cr", "*", "cipherBlockReader", ")", "ReadByte", "(", ")", "(", "byte", ",", "error", ")", "{", "for", "{", "if", "cr", ".", "n", "<", "len", "(", "cr", ".", "outbuf", ")", "{", "c", ":=", "cr", ".", "outbuf", "[", "cr", ".", "n", "]", "\n", "cr", ".", "n", "++", "\n", "return", "c", ",", "nil", "\n", "}", "\n", "if", "cr", ".", "err", "!=", "nil", "{", "err", ":=", "cr", ".", "err", "\n", "cr", ".", "err", "=", "nil", "\n", "return", "0", ",", "err", "\n", "}", "\n", "var", "n", "int", "\n", "n", ",", "cr", ".", "err", "=", "cr", ".", "read", "(", "cr", ".", "outbuf", "[", ":", "cap", "(", "cr", ".", "outbuf", ")", "]", ")", "\n", "cr", ".", "outbuf", "=", "cr", ".", "outbuf", "[", ":", "n", "]", "\n", "cr", ".", "n", "=", "0", "\n", "}", "\n", "}" ]
// ReadByte returns the next decrypted byte.
[ "ReadByte", "returns", "the", "next", "decrypted", "byte", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decrypt_reader.go#L87-L105
test
nwaples/rardecode
decrypt_reader.go
newCipherBlockReader
func newCipherBlockReader(r io.Reader, mode cipher.BlockMode) *cipherBlockReader { cr := &cipherBlockReader{r: r, mode: mode} cr.outbuf = make([]byte, 0, mode.BlockSize()) cr.inbuf = make([]byte, 0, mode.BlockSize()) return cr }
go
func newCipherBlockReader(r io.Reader, mode cipher.BlockMode) *cipherBlockReader { cr := &cipherBlockReader{r: r, mode: mode} cr.outbuf = make([]byte, 0, mode.BlockSize()) cr.inbuf = make([]byte, 0, mode.BlockSize()) return cr }
[ "func", "newCipherBlockReader", "(", "r", "io", ".", "Reader", ",", "mode", "cipher", ".", "BlockMode", ")", "*", "cipherBlockReader", "{", "cr", ":=", "&", "cipherBlockReader", "{", "r", ":", "r", ",", "mode", ":", "mode", "}", "\n", "cr", ".", "outbuf", "=", "make", "(", "[", "]", "byte", ",", "0", ",", "mode", ".", "BlockSize", "(", ")", ")", "\n", "cr", ".", "inbuf", "=", "make", "(", "[", "]", "byte", ",", "0", ",", "mode", ".", "BlockSize", "(", ")", ")", "\n", "return", "cr", "\n", "}" ]
// newCipherBlockReader returns a cipherBlockReader that decrypts the given io.Reader using // the provided block mode cipher.
[ "newCipherBlockReader", "returns", "a", "cipherBlockReader", "that", "decrypts", "the", "given", "io", ".", "Reader", "using", "the", "provided", "block", "mode", "cipher", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decrypt_reader.go#L109-L114
test
nwaples/rardecode
decrypt_reader.go
newAesDecryptReader
func newAesDecryptReader(r io.Reader, key, iv []byte) *cipherBlockReader { block, err := aes.NewCipher(key) if err != nil { panic(err) } mode := cipher.NewCBCDecrypter(block, iv) return newCipherBlockReader(r, mode) }
go
func newAesDecryptReader(r io.Reader, key, iv []byte) *cipherBlockReader { block, err := aes.NewCipher(key) if err != nil { panic(err) } mode := cipher.NewCBCDecrypter(block, iv) return newCipherBlockReader(r, mode) }
[ "func", "newAesDecryptReader", "(", "r", "io", ".", "Reader", ",", "key", ",", "iv", "[", "]", "byte", ")", "*", "cipherBlockReader", "{", "block", ",", "err", ":=", "aes", ".", "NewCipher", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "mode", ":=", "cipher", ".", "NewCBCDecrypter", "(", "block", ",", "iv", ")", "\n", "return", "newCipherBlockReader", "(", "r", ",", "mode", ")", "\n", "}" ]
// newAesDecryptReader returns a cipherBlockReader that decrypts input from a given io.Reader using AES. // It will panic if the provided key is invalid.
[ "newAesDecryptReader", "returns", "a", "cipherBlockReader", "that", "decrypts", "input", "from", "a", "given", "io", ".", "Reader", "using", "AES", ".", "It", "will", "panic", "if", "the", "provided", "key", "is", "invalid", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decrypt_reader.go#L118-L126
test
nwaples/rardecode
reader.go
limitByteReader
func limitByteReader(r byteReader, n int64) *limitedByteReader { return &limitedByteReader{limitedReader{r, n, io.ErrUnexpectedEOF}, r} }
go
func limitByteReader(r byteReader, n int64) *limitedByteReader { return &limitedByteReader{limitedReader{r, n, io.ErrUnexpectedEOF}, r} }
[ "func", "limitByteReader", "(", "r", "byteReader", ",", "n", "int64", ")", "*", "limitedByteReader", "{", "return", "&", "limitedByteReader", "{", "limitedReader", "{", "r", ",", "n", ",", "io", ".", "ErrUnexpectedEOF", "}", ",", "r", "}", "\n", "}" ]
// limitByteReader returns a limitedByteReader that reads from r and stops with // io.EOF after n bytes. // If r returns an io.EOF before reading n bytes, io.ErrUnexpectedEOF is returned.
[ "limitByteReader", "returns", "a", "limitedByteReader", "that", "reads", "from", "r", "and", "stops", "with", "io", ".", "EOF", "after", "n", "bytes", ".", "If", "r", "returns", "an", "io", ".", "EOF", "before", "reading", "n", "bytes", "io", ".", "ErrUnexpectedEOF", "is", "returned", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L82-L84
test
nwaples/rardecode
reader.go
Mode
func (f *FileHeader) Mode() os.FileMode { var m os.FileMode if f.IsDir { m = os.ModeDir } if f.HostOS == HostOSWindows { if f.IsDir { m |= 0777 } else if f.Attributes&1 > 0 { m |= 0444 // readonly } else { m |= 0666 } return m } // assume unix perms for all remaining os types m |= os.FileMode(f.Attributes) & os.ModePerm // only check other bits on unix host created archives if f.HostOS != HostOSUnix { return m } if f.Attributes&0x200 != 0 { m |= os.ModeSticky } if f.Attributes&0x400 != 0 { m |= os.ModeSetgid } if f.Attributes&0x800 != 0 { m |= os.ModeSetuid } // Check for additional file types. if f.Attributes&0xF000 == 0xA000 { m |= os.ModeSymlink } return m }
go
func (f *FileHeader) Mode() os.FileMode { var m os.FileMode if f.IsDir { m = os.ModeDir } if f.HostOS == HostOSWindows { if f.IsDir { m |= 0777 } else if f.Attributes&1 > 0 { m |= 0444 // readonly } else { m |= 0666 } return m } // assume unix perms for all remaining os types m |= os.FileMode(f.Attributes) & os.ModePerm // only check other bits on unix host created archives if f.HostOS != HostOSUnix { return m } if f.Attributes&0x200 != 0 { m |= os.ModeSticky } if f.Attributes&0x400 != 0 { m |= os.ModeSetgid } if f.Attributes&0x800 != 0 { m |= os.ModeSetuid } // Check for additional file types. if f.Attributes&0xF000 == 0xA000 { m |= os.ModeSymlink } return m }
[ "func", "(", "f", "*", "FileHeader", ")", "Mode", "(", ")", "os", ".", "FileMode", "{", "var", "m", "os", ".", "FileMode", "\n", "if", "f", ".", "IsDir", "{", "m", "=", "os", ".", "ModeDir", "\n", "}", "\n", "if", "f", ".", "HostOS", "==", "HostOSWindows", "{", "if", "f", ".", "IsDir", "{", "m", "|=", "0777", "\n", "}", "else", "if", "f", ".", "Attributes", "&", "1", ">", "0", "{", "m", "|=", "0444", "\n", "}", "else", "{", "m", "|=", "0666", "\n", "}", "\n", "return", "m", "\n", "}", "\n", "m", "|=", "os", ".", "FileMode", "(", "f", ".", "Attributes", ")", "&", "os", ".", "ModePerm", "\n", "if", "f", ".", "HostOS", "!=", "HostOSUnix", "{", "return", "m", "\n", "}", "\n", "if", "f", ".", "Attributes", "&", "0x200", "!=", "0", "{", "m", "|=", "os", ".", "ModeSticky", "\n", "}", "\n", "if", "f", ".", "Attributes", "&", "0x400", "!=", "0", "{", "m", "|=", "os", ".", "ModeSetgid", "\n", "}", "\n", "if", "f", ".", "Attributes", "&", "0x800", "!=", "0", "{", "m", "|=", "os", ".", "ModeSetuid", "\n", "}", "\n", "if", "f", ".", "Attributes", "&", "0xF000", "==", "0xA000", "{", "m", "|=", "os", ".", "ModeSymlink", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Mode returns an os.FileMode for the file, calculated from the Attributes field.
[ "Mode", "returns", "an", "os", ".", "FileMode", "for", "the", "file", "calculated", "from", "the", "Attributes", "field", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L111-L150
test
nwaples/rardecode
reader.go
nextBlockInFile
func (f *packedFileReader) nextBlockInFile() error { h, err := f.r.next() if err != nil { if err == io.EOF { // archive ended, but file hasn't return errUnexpectedArcEnd } return err } if h.first || h.Name != f.h.Name { return errInvalidFileBlock } f.h = h return nil }
go
func (f *packedFileReader) nextBlockInFile() error { h, err := f.r.next() if err != nil { if err == io.EOF { // archive ended, but file hasn't return errUnexpectedArcEnd } return err } if h.first || h.Name != f.h.Name { return errInvalidFileBlock } f.h = h return nil }
[ "func", "(", "f", "*", "packedFileReader", ")", "nextBlockInFile", "(", ")", "error", "{", "h", ",", "err", ":=", "f", ".", "r", ".", "next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "errUnexpectedArcEnd", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "if", "h", ".", "first", "||", "h", ".", "Name", "!=", "f", ".", "h", ".", "Name", "{", "return", "errInvalidFileBlock", "\n", "}", "\n", "f", ".", "h", "=", "h", "\n", "return", "nil", "\n", "}" ]
// nextBlockInFile reads the next file block in the current file at the current // archive file position, or returns an error if there is a problem. // It is invalid to call this when already at the last block in the current file.
[ "nextBlockInFile", "reads", "the", "next", "file", "block", "in", "the", "current", "file", "at", "the", "current", "archive", "file", "position", "or", "returns", "an", "error", "if", "there", "is", "a", "problem", ".", "It", "is", "invalid", "to", "call", "this", "when", "already", "at", "the", "last", "block", "in", "the", "current", "file", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L186-L200
test
nwaples/rardecode
reader.go
next
func (f *packedFileReader) next() (*fileBlockHeader, error) { if f.h != nil { // skip to last block in current file for !f.h.last { // discard remaining block data if _, err := io.Copy(ioutil.Discard, f.r); err != nil { return nil, err } if err := f.nextBlockInFile(); err != nil { return nil, err } } // discard last block data if _, err := io.Copy(ioutil.Discard, f.r); err != nil { return nil, err } } var err error f.h, err = f.r.next() // get next file block if err != nil { if err == errArchiveEnd { return nil, io.EOF } return nil, err } if !f.h.first { return nil, errInvalidFileBlock } return f.h, nil }
go
func (f *packedFileReader) next() (*fileBlockHeader, error) { if f.h != nil { // skip to last block in current file for !f.h.last { // discard remaining block data if _, err := io.Copy(ioutil.Discard, f.r); err != nil { return nil, err } if err := f.nextBlockInFile(); err != nil { return nil, err } } // discard last block data if _, err := io.Copy(ioutil.Discard, f.r); err != nil { return nil, err } } var err error f.h, err = f.r.next() // get next file block if err != nil { if err == errArchiveEnd { return nil, io.EOF } return nil, err } if !f.h.first { return nil, errInvalidFileBlock } return f.h, nil }
[ "func", "(", "f", "*", "packedFileReader", ")", "next", "(", ")", "(", "*", "fileBlockHeader", ",", "error", ")", "{", "if", "f", ".", "h", "!=", "nil", "{", "for", "!", "f", ".", "h", ".", "last", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "f", ".", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "f", ".", "nextBlockInFile", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "f", ".", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "var", "err", "error", "\n", "f", ".", "h", ",", "err", "=", "f", ".", "r", ".", "next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "errArchiveEnd", "{", "return", "nil", ",", "io", ".", "EOF", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "f", ".", "h", ".", "first", "{", "return", "nil", ",", "errInvalidFileBlock", "\n", "}", "\n", "return", "f", ".", "h", ",", "nil", "\n", "}" ]
// next advances to the next packed file in the RAR archive.
[ "next", "advances", "to", "the", "next", "packed", "file", "in", "the", "RAR", "archive", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L203-L232
test
nwaples/rardecode
reader.go
Read
func (f *packedFileReader) Read(p []byte) (int, error) { n, err := f.r.Read(p) // read current block data for err == io.EOF { // current block empty if n > 0 { return n, nil } if f.h == nil || f.h.last { return 0, io.EOF // last block so end of file } if err := f.nextBlockInFile(); err != nil { return 0, err } n, err = f.r.Read(p) // read new block data } return n, err }
go
func (f *packedFileReader) Read(p []byte) (int, error) { n, err := f.r.Read(p) // read current block data for err == io.EOF { // current block empty if n > 0 { return n, nil } if f.h == nil || f.h.last { return 0, io.EOF // last block so end of file } if err := f.nextBlockInFile(); err != nil { return 0, err } n, err = f.r.Read(p) // read new block data } return n, err }
[ "func", "(", "f", "*", "packedFileReader", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "f", ".", "r", ".", "Read", "(", "p", ")", "\n", "for", "err", "==", "io", ".", "EOF", "{", "if", "n", ">", "0", "{", "return", "n", ",", "nil", "\n", "}", "\n", "if", "f", ".", "h", "==", "nil", "||", "f", ".", "h", ".", "last", "{", "return", "0", ",", "io", ".", "EOF", "\n", "}", "\n", "if", "err", ":=", "f", ".", "nextBlockInFile", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "n", ",", "err", "=", "f", ".", "r", ".", "Read", "(", "p", ")", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Read reads the packed data for the current file into p.
[ "Read", "reads", "the", "packed", "data", "for", "the", "current", "file", "into", "p", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L235-L250
test
nwaples/rardecode
reader.go
Read
func (r *Reader) Read(p []byte) (int, error) { n, err := r.r.Read(p) if err == io.EOF && r.cksum != nil && !r.cksum.valid() { return n, errBadFileChecksum } return n, err }
go
func (r *Reader) Read(p []byte) (int, error) { n, err := r.r.Read(p) if err == io.EOF && r.cksum != nil && !r.cksum.valid() { return n, errBadFileChecksum } return n, err }
[ "func", "(", "r", "*", "Reader", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "r", ".", "r", ".", "Read", "(", "p", ")", "\n", "if", "err", "==", "io", ".", "EOF", "&&", "r", ".", "cksum", "!=", "nil", "&&", "!", "r", ".", "cksum", ".", "valid", "(", ")", "{", "return", "n", ",", "errBadFileChecksum", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Read reads from the current file in the RAR archive.
[ "Read", "reads", "from", "the", "current", "file", "in", "the", "RAR", "archive", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L273-L279
test
nwaples/rardecode
reader.go
Next
func (r *Reader) Next() (*FileHeader, error) { if r.solidr != nil { // solid files must be read fully to update decoder information if _, err := io.Copy(ioutil.Discard, r.solidr); err != nil { return nil, err } } h, err := r.pr.next() // skip to next file if err != nil { return nil, err } r.solidr = nil br := byteReader(&r.pr) // start with packed file reader // check for encryption if len(h.key) > 0 && len(h.iv) > 0 { br = newAesDecryptReader(br, h.key, h.iv) // decrypt } r.r = br // check for compression if h.decoder != nil { err = r.dr.init(br, h.decoder, h.winSize, !h.solid) if err != nil { return nil, err } r.r = &r.dr if r.pr.r.isSolid() { r.solidr = r.r } } if h.UnPackedSize >= 0 && !h.UnKnownSize { // Limit reading to UnPackedSize as there may be padding r.r = &limitedReader{r.r, h.UnPackedSize, errShortFile} } r.cksum = h.cksum if r.cksum != nil { r.r = io.TeeReader(r.r, h.cksum) // write file data to checksum as it is read } fh := new(FileHeader) *fh = h.FileHeader return fh, nil }
go
func (r *Reader) Next() (*FileHeader, error) { if r.solidr != nil { // solid files must be read fully to update decoder information if _, err := io.Copy(ioutil.Discard, r.solidr); err != nil { return nil, err } } h, err := r.pr.next() // skip to next file if err != nil { return nil, err } r.solidr = nil br := byteReader(&r.pr) // start with packed file reader // check for encryption if len(h.key) > 0 && len(h.iv) > 0 { br = newAesDecryptReader(br, h.key, h.iv) // decrypt } r.r = br // check for compression if h.decoder != nil { err = r.dr.init(br, h.decoder, h.winSize, !h.solid) if err != nil { return nil, err } r.r = &r.dr if r.pr.r.isSolid() { r.solidr = r.r } } if h.UnPackedSize >= 0 && !h.UnKnownSize { // Limit reading to UnPackedSize as there may be padding r.r = &limitedReader{r.r, h.UnPackedSize, errShortFile} } r.cksum = h.cksum if r.cksum != nil { r.r = io.TeeReader(r.r, h.cksum) // write file data to checksum as it is read } fh := new(FileHeader) *fh = h.FileHeader return fh, nil }
[ "func", "(", "r", "*", "Reader", ")", "Next", "(", ")", "(", "*", "FileHeader", ",", "error", ")", "{", "if", "r", ".", "solidr", "!=", "nil", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "r", ".", "solidr", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "h", ",", "err", ":=", "r", ".", "pr", ".", "next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "r", ".", "solidr", "=", "nil", "\n", "br", ":=", "byteReader", "(", "&", "r", ".", "pr", ")", "\n", "if", "len", "(", "h", ".", "key", ")", ">", "0", "&&", "len", "(", "h", ".", "iv", ")", ">", "0", "{", "br", "=", "newAesDecryptReader", "(", "br", ",", "h", ".", "key", ",", "h", ".", "iv", ")", "\n", "}", "\n", "r", ".", "r", "=", "br", "\n", "if", "h", ".", "decoder", "!=", "nil", "{", "err", "=", "r", ".", "dr", ".", "init", "(", "br", ",", "h", ".", "decoder", ",", "h", ".", "winSize", ",", "!", "h", ".", "solid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "r", ".", "r", "=", "&", "r", ".", "dr", "\n", "if", "r", ".", "pr", ".", "r", ".", "isSolid", "(", ")", "{", "r", ".", "solidr", "=", "r", ".", "r", "\n", "}", "\n", "}", "\n", "if", "h", ".", "UnPackedSize", ">=", "0", "&&", "!", "h", ".", "UnKnownSize", "{", "r", ".", "r", "=", "&", "limitedReader", "{", "r", ".", "r", ",", "h", ".", "UnPackedSize", ",", "errShortFile", "}", "\n", "}", "\n", "r", ".", "cksum", "=", "h", ".", "cksum", "\n", "if", "r", ".", "cksum", "!=", "nil", "{", "r", ".", "r", "=", "io", ".", "TeeReader", "(", "r", ".", "r", ",", "h", ".", "cksum", ")", "\n", "}", "\n", "fh", ":=", "new", "(", "FileHeader", ")", "\n", "*", "fh", "=", "h", ".", "FileHeader", "\n", "return", "fh", ",", "nil", "\n", "}" ]
// Next advances to the next file in the archive.
[ "Next", "advances", "to", "the", "next", "file", "in", "the", "archive", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L282-L325
test
nwaples/rardecode
reader.go
NewReader
func NewReader(r io.Reader, password string) (*Reader, error) { br, ok := r.(*bufio.Reader) if !ok { br = bufio.NewReader(r) } fbr, err := newFileBlockReader(br, password) if err != nil { return nil, err } rr := new(Reader) rr.init(fbr) return rr, nil }
go
func NewReader(r io.Reader, password string) (*Reader, error) { br, ok := r.(*bufio.Reader) if !ok { br = bufio.NewReader(r) } fbr, err := newFileBlockReader(br, password) if err != nil { return nil, err } rr := new(Reader) rr.init(fbr) return rr, nil }
[ "func", "NewReader", "(", "r", "io", ".", "Reader", ",", "password", "string", ")", "(", "*", "Reader", ",", "error", ")", "{", "br", ",", "ok", ":=", "r", ".", "(", "*", "bufio", ".", "Reader", ")", "\n", "if", "!", "ok", "{", "br", "=", "bufio", ".", "NewReader", "(", "r", ")", "\n", "}", "\n", "fbr", ",", "err", ":=", "newFileBlockReader", "(", "br", ",", "password", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "rr", ":=", "new", "(", "Reader", ")", "\n", "rr", ".", "init", "(", "fbr", ")", "\n", "return", "rr", ",", "nil", "\n", "}" ]
// NewReader creates a Reader reading from r. // NewReader only supports single volume archives. // Multi-volume archives must use OpenReader.
[ "NewReader", "creates", "a", "Reader", "reading", "from", "r", ".", "NewReader", "only", "supports", "single", "volume", "archives", ".", "Multi", "-", "volume", "archives", "must", "use", "OpenReader", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L335-L347
test
nwaples/rardecode
reader.go
OpenReader
func OpenReader(name, password string) (*ReadCloser, error) { v, err := openVolume(name, password) if err != nil { return nil, err } rc := new(ReadCloser) rc.v = v rc.Reader.init(v) return rc, nil }
go
func OpenReader(name, password string) (*ReadCloser, error) { v, err := openVolume(name, password) if err != nil { return nil, err } rc := new(ReadCloser) rc.v = v rc.Reader.init(v) return rc, nil }
[ "func", "OpenReader", "(", "name", ",", "password", "string", ")", "(", "*", "ReadCloser", ",", "error", ")", "{", "v", ",", "err", ":=", "openVolume", "(", "name", ",", "password", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "rc", ":=", "new", "(", "ReadCloser", ")", "\n", "rc", ".", "v", "=", "v", "\n", "rc", ".", "Reader", ".", "init", "(", "v", ")", "\n", "return", "rc", ",", "nil", "\n", "}" ]
// OpenReader opens a RAR archive specified by the name and returns a ReadCloser.
[ "OpenReader", "opens", "a", "RAR", "archive", "specified", "by", "the", "name", "and", "returns", "a", "ReadCloser", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L367-L376
test
nwaples/rardecode
filters.go
getV3Filter
func getV3Filter(code []byte) (v3Filter, error) { // check if filter is a known standard filter c := crc32.ChecksumIEEE(code) for _, f := range standardV3Filters { if f.crc == c && f.len == len(code) { return f.f, nil } } // create new vm filter f := new(vmFilter) r := newRarBitReader(bytes.NewReader(code[1:])) // skip first xor byte check // read static data n, err := r.readBits(1) if err != nil { return nil, err } if n > 0 { m, err := r.readUint32() if err != nil { return nil, err } f.static = make([]byte, m+1) err = r.readFull(f.static) if err != nil { return nil, err } } f.code, err = readCommands(r) if err == io.EOF { err = nil } return f.execute, err }
go
func getV3Filter(code []byte) (v3Filter, error) { // check if filter is a known standard filter c := crc32.ChecksumIEEE(code) for _, f := range standardV3Filters { if f.crc == c && f.len == len(code) { return f.f, nil } } // create new vm filter f := new(vmFilter) r := newRarBitReader(bytes.NewReader(code[1:])) // skip first xor byte check // read static data n, err := r.readBits(1) if err != nil { return nil, err } if n > 0 { m, err := r.readUint32() if err != nil { return nil, err } f.static = make([]byte, m+1) err = r.readFull(f.static) if err != nil { return nil, err } } f.code, err = readCommands(r) if err == io.EOF { err = nil } return f.execute, err }
[ "func", "getV3Filter", "(", "code", "[", "]", "byte", ")", "(", "v3Filter", ",", "error", ")", "{", "c", ":=", "crc32", ".", "ChecksumIEEE", "(", "code", ")", "\n", "for", "_", ",", "f", ":=", "range", "standardV3Filters", "{", "if", "f", ".", "crc", "==", "c", "&&", "f", ".", "len", "==", "len", "(", "code", ")", "{", "return", "f", ".", "f", ",", "nil", "\n", "}", "\n", "}", "\n", "f", ":=", "new", "(", "vmFilter", ")", "\n", "r", ":=", "newRarBitReader", "(", "bytes", ".", "NewReader", "(", "code", "[", "1", ":", "]", ")", ")", "\n", "n", ",", "err", ":=", "r", ".", "readBits", "(", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "n", ">", "0", "{", "m", ",", "err", ":=", "r", ".", "readUint32", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "f", ".", "static", "=", "make", "(", "[", "]", "byte", ",", "m", "+", "1", ")", "\n", "err", "=", "r", ".", "readFull", "(", "f", ".", "static", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "f", ".", "code", ",", "err", "=", "readCommands", "(", "r", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "err", "=", "nil", "\n", "}", "\n", "return", "f", ".", "execute", ",", "err", "\n", "}" ]
// getV3Filter returns a V3 filter function from a code byte slice.
[ "getV3Filter", "returns", "a", "V3", "filter", "function", "from", "a", "code", "byte", "slice", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/filters.go#L380-L416
test
nwaples/rardecode
decode29.go
init
func (d *decoder29) init(r io.ByteReader, reset bool) error { if d.br == nil { d.br = newRarBitReader(r) } else { d.br.reset(r) } d.eof = false if reset { d.initFilters() d.lz.reset() d.ppm.reset() d.decode = nil } if d.decode == nil { return d.readBlockHeader() } return nil }
go
func (d *decoder29) init(r io.ByteReader, reset bool) error { if d.br == nil { d.br = newRarBitReader(r) } else { d.br.reset(r) } d.eof = false if reset { d.initFilters() d.lz.reset() d.ppm.reset() d.decode = nil } if d.decode == nil { return d.readBlockHeader() } return nil }
[ "func", "(", "d", "*", "decoder29", ")", "init", "(", "r", "io", ".", "ByteReader", ",", "reset", "bool", ")", "error", "{", "if", "d", ".", "br", "==", "nil", "{", "d", ".", "br", "=", "newRarBitReader", "(", "r", ")", "\n", "}", "else", "{", "d", ".", "br", ".", "reset", "(", "r", ")", "\n", "}", "\n", "d", ".", "eof", "=", "false", "\n", "if", "reset", "{", "d", ".", "initFilters", "(", ")", "\n", "d", ".", "lz", ".", "reset", "(", ")", "\n", "d", ".", "ppm", ".", "reset", "(", ")", "\n", "d", ".", "decode", "=", "nil", "\n", "}", "\n", "if", "d", ".", "decode", "==", "nil", "{", "return", "d", ".", "readBlockHeader", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// init intializes the decoder for decoding a new file.
[ "init", "intializes", "the", "decoder", "for", "decoding", "a", "new", "file", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decode29.go#L43-L60
test
nwaples/rardecode
decode29.go
readBlockHeader
func (d *decoder29) readBlockHeader() error { d.br.alignByte() n, err := d.br.readBits(1) if err == nil { if n > 0 { d.decode = d.ppm.decode err = d.ppm.init(d.br) } else { d.decode = d.lz.decode err = d.lz.init(d.br) } } if err == io.EOF { err = errDecoderOutOfData } return err }
go
func (d *decoder29) readBlockHeader() error { d.br.alignByte() n, err := d.br.readBits(1) if err == nil { if n > 0 { d.decode = d.ppm.decode err = d.ppm.init(d.br) } else { d.decode = d.lz.decode err = d.lz.init(d.br) } } if err == io.EOF { err = errDecoderOutOfData } return err }
[ "func", "(", "d", "*", "decoder29", ")", "readBlockHeader", "(", ")", "error", "{", "d", ".", "br", ".", "alignByte", "(", ")", "\n", "n", ",", "err", ":=", "d", ".", "br", ".", "readBits", "(", "1", ")", "\n", "if", "err", "==", "nil", "{", "if", "n", ">", "0", "{", "d", ".", "decode", "=", "d", ".", "ppm", ".", "decode", "\n", "err", "=", "d", ".", "ppm", ".", "init", "(", "d", ".", "br", ")", "\n", "}", "else", "{", "d", ".", "decode", "=", "d", ".", "lz", ".", "decode", "\n", "err", "=", "d", ".", "lz", ".", "init", "(", "d", ".", "br", ")", "\n", "}", "\n", "}", "\n", "if", "err", "==", "io", ".", "EOF", "{", "err", "=", "errDecoderOutOfData", "\n", "}", "\n", "return", "err", "\n", "}" ]
// readBlockHeader determines and initializes the current decoder for a new decode block.
[ "readBlockHeader", "determines", "and", "initializes", "the", "current", "decoder", "for", "a", "new", "decode", "block", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decode29.go#L203-L220
test
nwaples/rardecode
huffman.go
readCodeLengthTable
func readCodeLengthTable(br bitReader, codeLength []byte, addOld bool) error { var bitlength [20]byte for i := 0; i < len(bitlength); i++ { n, err := br.readBits(4) if err != nil { return err } if n == 0xf { cnt, err := br.readBits(4) if err != nil { return err } if cnt > 0 { // array already zero'd dont need to explicitly set i += cnt + 1 continue } } bitlength[i] = byte(n) } var bl huffmanDecoder bl.init(bitlength[:]) for i := 0; i < len(codeLength); i++ { l, err := bl.readSym(br) if err != nil { return err } if l < 16 { if addOld { codeLength[i] = (codeLength[i] + byte(l)) & 0xf } else { codeLength[i] = byte(l) } continue } var count int var value byte switch l { case 16, 18: count, err = br.readBits(3) count += 3 default: count, err = br.readBits(7) count += 11 } if err != nil { return err } if l < 18 { if i == 0 { return errInvalidLengthTable } value = codeLength[i-1] } for ; count > 0 && i < len(codeLength); i++ { codeLength[i] = value count-- } i-- } return nil }
go
func readCodeLengthTable(br bitReader, codeLength []byte, addOld bool) error { var bitlength [20]byte for i := 0; i < len(bitlength); i++ { n, err := br.readBits(4) if err != nil { return err } if n == 0xf { cnt, err := br.readBits(4) if err != nil { return err } if cnt > 0 { // array already zero'd dont need to explicitly set i += cnt + 1 continue } } bitlength[i] = byte(n) } var bl huffmanDecoder bl.init(bitlength[:]) for i := 0; i < len(codeLength); i++ { l, err := bl.readSym(br) if err != nil { return err } if l < 16 { if addOld { codeLength[i] = (codeLength[i] + byte(l)) & 0xf } else { codeLength[i] = byte(l) } continue } var count int var value byte switch l { case 16, 18: count, err = br.readBits(3) count += 3 default: count, err = br.readBits(7) count += 11 } if err != nil { return err } if l < 18 { if i == 0 { return errInvalidLengthTable } value = codeLength[i-1] } for ; count > 0 && i < len(codeLength); i++ { codeLength[i] = value count-- } i-- } return nil }
[ "func", "readCodeLengthTable", "(", "br", "bitReader", ",", "codeLength", "[", "]", "byte", ",", "addOld", "bool", ")", "error", "{", "var", "bitlength", "[", "20", "]", "byte", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "bitlength", ")", ";", "i", "++", "{", "n", ",", "err", ":=", "br", ".", "readBits", "(", "4", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "n", "==", "0xf", "{", "cnt", ",", "err", ":=", "br", ".", "readBits", "(", "4", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "cnt", ">", "0", "{", "i", "+=", "cnt", "+", "1", "\n", "continue", "\n", "}", "\n", "}", "\n", "bitlength", "[", "i", "]", "=", "byte", "(", "n", ")", "\n", "}", "\n", "var", "bl", "huffmanDecoder", "\n", "bl", ".", "init", "(", "bitlength", "[", ":", "]", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "codeLength", ")", ";", "i", "++", "{", "l", ",", "err", ":=", "bl", ".", "readSym", "(", "br", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "l", "<", "16", "{", "if", "addOld", "{", "codeLength", "[", "i", "]", "=", "(", "codeLength", "[", "i", "]", "+", "byte", "(", "l", ")", ")", "&", "0xf", "\n", "}", "else", "{", "codeLength", "[", "i", "]", "=", "byte", "(", "l", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "var", "count", "int", "\n", "var", "value", "byte", "\n", "switch", "l", "{", "case", "16", ",", "18", ":", "count", ",", "err", "=", "br", ".", "readBits", "(", "3", ")", "\n", "count", "+=", "3", "\n", "default", ":", "count", ",", "err", "=", "br", ".", "readBits", "(", "7", ")", "\n", "count", "+=", "11", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "l", "<", "18", "{", "if", "i", "==", "0", "{", "return", "errInvalidLengthTable", "\n", "}", "\n", "value", "=", "codeLength", "[", "i", "-", "1", "]", "\n", "}", "\n", "for", ";", "count", ">", "0", "&&", "i", "<", "len", "(", "codeLength", ")", ";", "i", "++", "{", "codeLength", "[", "i", "]", "=", "value", "\n", "count", "--", "\n", "}", "\n", "i", "--", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// readCodeLengthTable reads a new code length table into codeLength from br. // If addOld is set the old table is added to the new one.
[ "readCodeLengthTable", "reads", "a", "new", "code", "length", "table", "into", "codeLength", "from", "br", ".", "If", "addOld", "is", "set", "the", "old", "table", "is", "added", "to", "the", "new", "one", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/huffman.go#L142-L208
test
nwaples/rardecode
ppm_model.go
shrinkStates
func (c *context) shrinkStates(states []state, size int) []state { i1 := units2Index[(len(states)+1)>>1] i2 := units2Index[(size+1)>>1] if size == 1 { // store state in context, and free states block n := c.statesIndex() c.s[1] = states[0] states = c.s[1:] c.a.addFreeBlock(n, i1) } else if i1 != i2 { if n := c.a.removeFreeBlock(i2); n > 0 { // allocate new block and copy copy(c.a.states[n:], states[:size]) states = c.a.states[n:] // free old block c.a.addFreeBlock(c.statesIndex(), i1) c.setStatesIndex(n) } else { // split current block, and free units not needed n = c.statesIndex() + index2Units[i2]<<1 u := index2Units[i1] - index2Units[i2] c.a.freeUnits(n, u) } } c.setNumStates(size) return states[:size] }
go
func (c *context) shrinkStates(states []state, size int) []state { i1 := units2Index[(len(states)+1)>>1] i2 := units2Index[(size+1)>>1] if size == 1 { // store state in context, and free states block n := c.statesIndex() c.s[1] = states[0] states = c.s[1:] c.a.addFreeBlock(n, i1) } else if i1 != i2 { if n := c.a.removeFreeBlock(i2); n > 0 { // allocate new block and copy copy(c.a.states[n:], states[:size]) states = c.a.states[n:] // free old block c.a.addFreeBlock(c.statesIndex(), i1) c.setStatesIndex(n) } else { // split current block, and free units not needed n = c.statesIndex() + index2Units[i2]<<1 u := index2Units[i1] - index2Units[i2] c.a.freeUnits(n, u) } } c.setNumStates(size) return states[:size] }
[ "func", "(", "c", "*", "context", ")", "shrinkStates", "(", "states", "[", "]", "state", ",", "size", "int", ")", "[", "]", "state", "{", "i1", ":=", "units2Index", "[", "(", "len", "(", "states", ")", "+", "1", ")", ">>", "1", "]", "\n", "i2", ":=", "units2Index", "[", "(", "size", "+", "1", ")", ">>", "1", "]", "\n", "if", "size", "==", "1", "{", "n", ":=", "c", ".", "statesIndex", "(", ")", "\n", "c", ".", "s", "[", "1", "]", "=", "states", "[", "0", "]", "\n", "states", "=", "c", ".", "s", "[", "1", ":", "]", "\n", "c", ".", "a", ".", "addFreeBlock", "(", "n", ",", "i1", ")", "\n", "}", "else", "if", "i1", "!=", "i2", "{", "if", "n", ":=", "c", ".", "a", ".", "removeFreeBlock", "(", "i2", ")", ";", "n", ">", "0", "{", "copy", "(", "c", ".", "a", ".", "states", "[", "n", ":", "]", ",", "states", "[", ":", "size", "]", ")", "\n", "states", "=", "c", ".", "a", ".", "states", "[", "n", ":", "]", "\n", "c", ".", "a", ".", "addFreeBlock", "(", "c", ".", "statesIndex", "(", ")", ",", "i1", ")", "\n", "c", ".", "setStatesIndex", "(", "n", ")", "\n", "}", "else", "{", "n", "=", "c", ".", "statesIndex", "(", ")", "+", "index2Units", "[", "i2", "]", "<<", "1", "\n", "u", ":=", "index2Units", "[", "i1", "]", "-", "index2Units", "[", "i2", "]", "\n", "c", ".", "a", ".", "freeUnits", "(", "n", ",", "u", ")", "\n", "}", "\n", "}", "\n", "c", ".", "setNumStates", "(", "size", ")", "\n", "return", "states", "[", ":", "size", "]", "\n", "}" ]
// shrinkStates shrinks the state list down to size states
[ "shrinkStates", "shrinks", "the", "state", "list", "down", "to", "size", "states" ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/ppm_model.go#L232-L259
test
nwaples/rardecode
ppm_model.go
expandStates
func (c *context) expandStates() []state { states := c.states() ns := len(states) if ns == 1 { s := states[0] n := c.a.allocUnits(1) if n == 0 { return nil } c.setStatesIndex(n) states = c.a.states[n:] states[0] = s } else if ns&0x1 == 0 { u := ns >> 1 i1 := units2Index[u] i2 := units2Index[u+1] if i1 != i2 { n := c.a.allocUnits(i2) if n == 0 { return nil } copy(c.a.states[n:], states) c.a.addFreeBlock(c.statesIndex(), i1) c.setStatesIndex(n) states = c.a.states[n:] } } c.setNumStates(ns + 1) return states[:ns+1] }
go
func (c *context) expandStates() []state { states := c.states() ns := len(states) if ns == 1 { s := states[0] n := c.a.allocUnits(1) if n == 0 { return nil } c.setStatesIndex(n) states = c.a.states[n:] states[0] = s } else if ns&0x1 == 0 { u := ns >> 1 i1 := units2Index[u] i2 := units2Index[u+1] if i1 != i2 { n := c.a.allocUnits(i2) if n == 0 { return nil } copy(c.a.states[n:], states) c.a.addFreeBlock(c.statesIndex(), i1) c.setStatesIndex(n) states = c.a.states[n:] } } c.setNumStates(ns + 1) return states[:ns+1] }
[ "func", "(", "c", "*", "context", ")", "expandStates", "(", ")", "[", "]", "state", "{", "states", ":=", "c", ".", "states", "(", ")", "\n", "ns", ":=", "len", "(", "states", ")", "\n", "if", "ns", "==", "1", "{", "s", ":=", "states", "[", "0", "]", "\n", "n", ":=", "c", ".", "a", ".", "allocUnits", "(", "1", ")", "\n", "if", "n", "==", "0", "{", "return", "nil", "\n", "}", "\n", "c", ".", "setStatesIndex", "(", "n", ")", "\n", "states", "=", "c", ".", "a", ".", "states", "[", "n", ":", "]", "\n", "states", "[", "0", "]", "=", "s", "\n", "}", "else", "if", "ns", "&", "0x1", "==", "0", "{", "u", ":=", "ns", ">>", "1", "\n", "i1", ":=", "units2Index", "[", "u", "]", "\n", "i2", ":=", "units2Index", "[", "u", "+", "1", "]", "\n", "if", "i1", "!=", "i2", "{", "n", ":=", "c", ".", "a", ".", "allocUnits", "(", "i2", ")", "\n", "if", "n", "==", "0", "{", "return", "nil", "\n", "}", "\n", "copy", "(", "c", ".", "a", ".", "states", "[", "n", ":", "]", ",", "states", ")", "\n", "c", ".", "a", ".", "addFreeBlock", "(", "c", ".", "statesIndex", "(", ")", ",", "i1", ")", "\n", "c", ".", "setStatesIndex", "(", "n", ")", "\n", "states", "=", "c", ".", "a", ".", "states", "[", "n", ":", "]", "\n", "}", "\n", "}", "\n", "c", ".", "setNumStates", "(", "ns", "+", "1", ")", "\n", "return", "states", "[", ":", "ns", "+", "1", "]", "\n", "}" ]
// expandStates expands the states list by one
[ "expandStates", "expands", "the", "states", "list", "by", "one" ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/ppm_model.go#L262-L291
test
nwaples/rardecode
ppm_model.go
pushByte
func (a *subAllocator) pushByte(c byte) int32 { si := a.heap1Lo / 6 // state index oi := a.heap1Lo % 6 // byte position in state switch oi { case 0: a.states[si].sym = c case 1: a.states[si].freq = c default: n := (uint(oi) - 2) * 8 mask := ^(uint32(0xFF) << n) succ := uint32(a.states[si].succ) & mask succ |= uint32(c) << n a.states[si].succ = int32(succ) } a.heap1Lo++ if a.heap1Lo >= a.heap1Hi { return 0 } return -a.heap1Lo }
go
func (a *subAllocator) pushByte(c byte) int32 { si := a.heap1Lo / 6 // state index oi := a.heap1Lo % 6 // byte position in state switch oi { case 0: a.states[si].sym = c case 1: a.states[si].freq = c default: n := (uint(oi) - 2) * 8 mask := ^(uint32(0xFF) << n) succ := uint32(a.states[si].succ) & mask succ |= uint32(c) << n a.states[si].succ = int32(succ) } a.heap1Lo++ if a.heap1Lo >= a.heap1Hi { return 0 } return -a.heap1Lo }
[ "func", "(", "a", "*", "subAllocator", ")", "pushByte", "(", "c", "byte", ")", "int32", "{", "si", ":=", "a", ".", "heap1Lo", "/", "6", "\n", "oi", ":=", "a", ".", "heap1Lo", "%", "6", "\n", "switch", "oi", "{", "case", "0", ":", "a", ".", "states", "[", "si", "]", ".", "sym", "=", "c", "\n", "case", "1", ":", "a", ".", "states", "[", "si", "]", ".", "freq", "=", "c", "\n", "default", ":", "n", ":=", "(", "uint", "(", "oi", ")", "-", "2", ")", "*", "8", "\n", "mask", ":=", "^", "(", "uint32", "(", "0xFF", ")", "<<", "n", ")", "\n", "succ", ":=", "uint32", "(", "a", ".", "states", "[", "si", "]", ".", "succ", ")", "&", "mask", "\n", "succ", "|=", "uint32", "(", "c", ")", "<<", "n", "\n", "a", ".", "states", "[", "si", "]", ".", "succ", "=", "int32", "(", "succ", ")", "\n", "}", "\n", "a", ".", "heap1Lo", "++", "\n", "if", "a", ".", "heap1Lo", ">=", "a", ".", "heap1Hi", "{", "return", "0", "\n", "}", "\n", "return", "-", "a", ".", "heap1Lo", "\n", "}" ]
// pushByte puts a byte on the heap and returns a state.succ index that // can be used to retrieve it.
[ "pushByte", "puts", "a", "byte", "on", "the", "heap", "and", "returns", "a", "state", ".", "succ", "index", "that", "can", "be", "used", "to", "retrieve", "it", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/ppm_model.go#L350-L370
test
nwaples/rardecode
ppm_model.go
succByte
func (a *subAllocator) succByte(i int32) byte { i = -i si := i / 6 oi := i % 6 switch oi { case 0: return a.states[si].sym case 1: return a.states[si].freq default: n := (uint(oi) - 2) * 8 succ := uint32(a.states[si].succ) >> n return byte(succ & 0xff) } }
go
func (a *subAllocator) succByte(i int32) byte { i = -i si := i / 6 oi := i % 6 switch oi { case 0: return a.states[si].sym case 1: return a.states[si].freq default: n := (uint(oi) - 2) * 8 succ := uint32(a.states[si].succ) >> n return byte(succ & 0xff) } }
[ "func", "(", "a", "*", "subAllocator", ")", "succByte", "(", "i", "int32", ")", "byte", "{", "i", "=", "-", "i", "\n", "si", ":=", "i", "/", "6", "\n", "oi", ":=", "i", "%", "6", "\n", "switch", "oi", "{", "case", "0", ":", "return", "a", ".", "states", "[", "si", "]", ".", "sym", "\n", "case", "1", ":", "return", "a", ".", "states", "[", "si", "]", ".", "freq", "\n", "default", ":", "n", ":=", "(", "uint", "(", "oi", ")", "-", "2", ")", "*", "8", "\n", "succ", ":=", "uint32", "(", "a", ".", "states", "[", "si", "]", ".", "succ", ")", ">>", "n", "\n", "return", "byte", "(", "succ", "&", "0xff", ")", "\n", "}", "\n", "}" ]
// succByte returns a byte from the heap given a state.succ index
[ "succByte", "returns", "a", "byte", "from", "the", "heap", "given", "a", "state", ".", "succ", "index" ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/ppm_model.go#L376-L390
test
nwaples/rardecode
ppm_model.go
succContext
func (a *subAllocator) succContext(i int32) *context { if i <= 0 { return nil } return &context{i: i, s: a.states[i : i+2 : i+2], a: a} }
go
func (a *subAllocator) succContext(i int32) *context { if i <= 0 { return nil } return &context{i: i, s: a.states[i : i+2 : i+2], a: a} }
[ "func", "(", "a", "*", "subAllocator", ")", "succContext", "(", "i", "int32", ")", "*", "context", "{", "if", "i", "<=", "0", "{", "return", "nil", "\n", "}", "\n", "return", "&", "context", "{", "i", ":", "i", ",", "s", ":", "a", ".", "states", "[", "i", ":", "i", "+", "2", ":", "i", "+", "2", "]", ",", "a", ":", "a", "}", "\n", "}" ]
// succContext returns a context given a state.succ index
[ "succContext", "returns", "a", "context", "given", "a", "state", ".", "succ", "index" ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/ppm_model.go#L393-L398
test
nwaples/rardecode
archive15.go
calcAes30Params
func calcAes30Params(pass []uint16, salt []byte) (key, iv []byte) { p := make([]byte, 0, len(pass)*2+len(salt)) for _, v := range pass { p = append(p, byte(v), byte(v>>8)) } p = append(p, salt...) hash := sha1.New() iv = make([]byte, 16) s := make([]byte, 0, hash.Size()) for i := 0; i < hashRounds; i++ { hash.Write(p) hash.Write([]byte{byte(i), byte(i >> 8), byte(i >> 16)}) if i%(hashRounds/16) == 0 { s = hash.Sum(s[:0]) iv[i/(hashRounds/16)] = s[4*4+3] } } key = hash.Sum(s[:0]) key = key[:16] for k := key; len(k) >= 4; k = k[4:] { k[0], k[1], k[2], k[3] = k[3], k[2], k[1], k[0] } return key, iv }
go
func calcAes30Params(pass []uint16, salt []byte) (key, iv []byte) { p := make([]byte, 0, len(pass)*2+len(salt)) for _, v := range pass { p = append(p, byte(v), byte(v>>8)) } p = append(p, salt...) hash := sha1.New() iv = make([]byte, 16) s := make([]byte, 0, hash.Size()) for i := 0; i < hashRounds; i++ { hash.Write(p) hash.Write([]byte{byte(i), byte(i >> 8), byte(i >> 16)}) if i%(hashRounds/16) == 0 { s = hash.Sum(s[:0]) iv[i/(hashRounds/16)] = s[4*4+3] } } key = hash.Sum(s[:0]) key = key[:16] for k := key; len(k) >= 4; k = k[4:] { k[0], k[1], k[2], k[3] = k[3], k[2], k[1], k[0] } return key, iv }
[ "func", "calcAes30Params", "(", "pass", "[", "]", "uint16", ",", "salt", "[", "]", "byte", ")", "(", "key", ",", "iv", "[", "]", "byte", ")", "{", "p", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "pass", ")", "*", "2", "+", "len", "(", "salt", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "pass", "{", "p", "=", "append", "(", "p", ",", "byte", "(", "v", ")", ",", "byte", "(", "v", ">>", "8", ")", ")", "\n", "}", "\n", "p", "=", "append", "(", "p", ",", "salt", "...", ")", "\n", "hash", ":=", "sha1", ".", "New", "(", ")", "\n", "iv", "=", "make", "(", "[", "]", "byte", ",", "16", ")", "\n", "s", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "hash", ".", "Size", "(", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "hashRounds", ";", "i", "++", "{", "hash", ".", "Write", "(", "p", ")", "\n", "hash", ".", "Write", "(", "[", "]", "byte", "{", "byte", "(", "i", ")", ",", "byte", "(", "i", ">>", "8", ")", ",", "byte", "(", "i", ">>", "16", ")", "}", ")", "\n", "if", "i", "%", "(", "hashRounds", "/", "16", ")", "==", "0", "{", "s", "=", "hash", ".", "Sum", "(", "s", "[", ":", "0", "]", ")", "\n", "iv", "[", "i", "/", "(", "hashRounds", "/", "16", ")", "]", "=", "s", "[", "4", "*", "4", "+", "3", "]", "\n", "}", "\n", "}", "\n", "key", "=", "hash", ".", "Sum", "(", "s", "[", ":", "0", "]", ")", "\n", "key", "=", "key", "[", ":", "16", "]", "\n", "for", "k", ":=", "key", ";", "len", "(", "k", ")", ">=", "4", ";", "k", "=", "k", "[", "4", ":", "]", "{", "k", "[", "0", "]", ",", "k", "[", "1", "]", ",", "k", "[", "2", "]", ",", "k", "[", "3", "]", "=", "k", "[", "3", "]", ",", "k", "[", "2", "]", ",", "k", "[", "1", "]", ",", "k", "[", "0", "]", "\n", "}", "\n", "return", "key", ",", "iv", "\n", "}" ]
// Calculates the key and iv for AES decryption given a password and salt.
[ "Calculates", "the", "key", "and", "iv", "for", "AES", "decryption", "given", "a", "password", "and", "salt", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive15.go#L96-L121
test
nwaples/rardecode
archive15.go
parseDosTime
func parseDosTime(t uint32) time.Time { n := int(t) sec := n & 0x1f << 1 min := n >> 5 & 0x3f hr := n >> 11 & 0x1f day := n >> 16 & 0x1f mon := time.Month(n >> 21 & 0x0f) yr := n>>25&0x7f + 1980 return time.Date(yr, mon, day, hr, min, sec, 0, time.Local) }
go
func parseDosTime(t uint32) time.Time { n := int(t) sec := n & 0x1f << 1 min := n >> 5 & 0x3f hr := n >> 11 & 0x1f day := n >> 16 & 0x1f mon := time.Month(n >> 21 & 0x0f) yr := n>>25&0x7f + 1980 return time.Date(yr, mon, day, hr, min, sec, 0, time.Local) }
[ "func", "parseDosTime", "(", "t", "uint32", ")", "time", ".", "Time", "{", "n", ":=", "int", "(", "t", ")", "\n", "sec", ":=", "n", "&", "0x1f", "<<", "1", "\n", "min", ":=", "n", ">>", "5", "&", "0x3f", "\n", "hr", ":=", "n", ">>", "11", "&", "0x1f", "\n", "day", ":=", "n", ">>", "16", "&", "0x1f", "\n", "mon", ":=", "time", ".", "Month", "(", "n", ">>", "21", "&", "0x0f", ")", "\n", "yr", ":=", "n", ">>", "25", "&", "0x7f", "+", "1980", "\n", "return", "time", ".", "Date", "(", "yr", ",", "mon", ",", "day", ",", "hr", ",", "min", ",", "sec", ",", "0", ",", "time", ".", "Local", ")", "\n", "}" ]
// parseDosTime converts a 32bit DOS time value to time.Time
[ "parseDosTime", "converts", "a", "32bit", "DOS", "time", "value", "to", "time", ".", "Time" ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive15.go#L124-L133
test
nwaples/rardecode
archive15.go
decodeName
func decodeName(buf []byte) string { i := bytes.IndexByte(buf, 0) if i < 0 { return string(buf) // filename is UTF-8 } name := buf[:i] encName := readBuf(buf[i+1:]) if len(encName) < 2 { return "" // invalid encoding } highByte := uint16(encName.byte()) << 8 flags := encName.byte() flagBits := 8 var wchars []uint16 // decoded characters are UTF-16 for len(wchars) < len(name) && len(encName) > 0 { if flagBits == 0 { flags = encName.byte() flagBits = 8 if len(encName) == 0 { break } } switch flags >> 6 { case 0: wchars = append(wchars, uint16(encName.byte())) case 1: wchars = append(wchars, uint16(encName.byte())|highByte) case 2: if len(encName) < 2 { break } wchars = append(wchars, encName.uint16()) case 3: n := encName.byte() b := name[len(wchars):] if l := int(n&0x7f) + 2; l < len(b) { b = b[:l] } if n&0x80 > 0 { if len(encName) < 1 { break } ec := encName.byte() for _, c := range b { wchars = append(wchars, uint16(c+ec)|highByte) } } else { for _, c := range b { wchars = append(wchars, uint16(c)) } } } flags <<= 2 flagBits -= 2 } return string(utf16.Decode(wchars)) }
go
func decodeName(buf []byte) string { i := bytes.IndexByte(buf, 0) if i < 0 { return string(buf) // filename is UTF-8 } name := buf[:i] encName := readBuf(buf[i+1:]) if len(encName) < 2 { return "" // invalid encoding } highByte := uint16(encName.byte()) << 8 flags := encName.byte() flagBits := 8 var wchars []uint16 // decoded characters are UTF-16 for len(wchars) < len(name) && len(encName) > 0 { if flagBits == 0 { flags = encName.byte() flagBits = 8 if len(encName) == 0 { break } } switch flags >> 6 { case 0: wchars = append(wchars, uint16(encName.byte())) case 1: wchars = append(wchars, uint16(encName.byte())|highByte) case 2: if len(encName) < 2 { break } wchars = append(wchars, encName.uint16()) case 3: n := encName.byte() b := name[len(wchars):] if l := int(n&0x7f) + 2; l < len(b) { b = b[:l] } if n&0x80 > 0 { if len(encName) < 1 { break } ec := encName.byte() for _, c := range b { wchars = append(wchars, uint16(c+ec)|highByte) } } else { for _, c := range b { wchars = append(wchars, uint16(c)) } } } flags <<= 2 flagBits -= 2 } return string(utf16.Decode(wchars)) }
[ "func", "decodeName", "(", "buf", "[", "]", "byte", ")", "string", "{", "i", ":=", "bytes", ".", "IndexByte", "(", "buf", ",", "0", ")", "\n", "if", "i", "<", "0", "{", "return", "string", "(", "buf", ")", "\n", "}", "\n", "name", ":=", "buf", "[", ":", "i", "]", "\n", "encName", ":=", "readBuf", "(", "buf", "[", "i", "+", "1", ":", "]", ")", "\n", "if", "len", "(", "encName", ")", "<", "2", "{", "return", "\"\"", "\n", "}", "\n", "highByte", ":=", "uint16", "(", "encName", ".", "byte", "(", ")", ")", "<<", "8", "\n", "flags", ":=", "encName", ".", "byte", "(", ")", "\n", "flagBits", ":=", "8", "\n", "var", "wchars", "[", "]", "uint16", "\n", "for", "len", "(", "wchars", ")", "<", "len", "(", "name", ")", "&&", "len", "(", "encName", ")", ">", "0", "{", "if", "flagBits", "==", "0", "{", "flags", "=", "encName", ".", "byte", "(", ")", "\n", "flagBits", "=", "8", "\n", "if", "len", "(", "encName", ")", "==", "0", "{", "break", "\n", "}", "\n", "}", "\n", "switch", "flags", ">>", "6", "{", "case", "0", ":", "wchars", "=", "append", "(", "wchars", ",", "uint16", "(", "encName", ".", "byte", "(", ")", ")", ")", "\n", "case", "1", ":", "wchars", "=", "append", "(", "wchars", ",", "uint16", "(", "encName", ".", "byte", "(", ")", ")", "|", "highByte", ")", "\n", "case", "2", ":", "if", "len", "(", "encName", ")", "<", "2", "{", "break", "\n", "}", "\n", "wchars", "=", "append", "(", "wchars", ",", "encName", ".", "uint16", "(", ")", ")", "\n", "case", "3", ":", "n", ":=", "encName", ".", "byte", "(", ")", "\n", "b", ":=", "name", "[", "len", "(", "wchars", ")", ":", "]", "\n", "if", "l", ":=", "int", "(", "n", "&", "0x7f", ")", "+", "2", ";", "l", "<", "len", "(", "b", ")", "{", "b", "=", "b", "[", ":", "l", "]", "\n", "}", "\n", "if", "n", "&", "0x80", ">", "0", "{", "if", "len", "(", "encName", ")", "<", "1", "{", "break", "\n", "}", "\n", "ec", ":=", "encName", ".", "byte", "(", ")", "\n", "for", "_", ",", "c", ":=", "range", "b", "{", "wchars", "=", "append", "(", "wchars", ",", "uint16", "(", "c", "+", "ec", ")", "|", "highByte", ")", "\n", "}", "\n", "}", "else", "{", "for", "_", ",", "c", ":=", "range", "b", "{", "wchars", "=", "append", "(", "wchars", ",", "uint16", "(", "c", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "flags", "<<=", "2", "\n", "flagBits", "-=", "2", "\n", "}", "\n", "return", "string", "(", "utf16", ".", "Decode", "(", "wchars", ")", ")", "\n", "}" ]
// decodeName decodes a non-unicode filename from a file header.
[ "decodeName", "decodes", "a", "non", "-", "unicode", "filename", "from", "a", "file", "header", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive15.go#L136-L193
test
nwaples/rardecode
archive15.go
readExtTimes
func readExtTimes(f *fileBlockHeader, b *readBuf) { if len(*b) < 2 { return // invalid, not enough data } flags := b.uint16() ts := []*time.Time{&f.ModificationTime, &f.CreationTime, &f.AccessTime} for i, t := range ts { n := flags >> uint((3-i)*4) if n&0x8 == 0 { continue } if i != 0 { // ModificationTime already read so skip if len(*b) < 4 { return // invalid, not enough data } *t = parseDosTime(b.uint32()) } if n&0x4 > 0 { *t = t.Add(time.Second) } n &= 0x3 if n == 0 { continue } if len(*b) < int(n) { return // invalid, not enough data } // add extra time data in 100's of nanoseconds d := time.Duration(0) for j := 3 - n; j < n; j++ { d |= time.Duration(b.byte()) << (j * 8) } d *= 100 *t = t.Add(d) } }
go
func readExtTimes(f *fileBlockHeader, b *readBuf) { if len(*b) < 2 { return // invalid, not enough data } flags := b.uint16() ts := []*time.Time{&f.ModificationTime, &f.CreationTime, &f.AccessTime} for i, t := range ts { n := flags >> uint((3-i)*4) if n&0x8 == 0 { continue } if i != 0 { // ModificationTime already read so skip if len(*b) < 4 { return // invalid, not enough data } *t = parseDosTime(b.uint32()) } if n&0x4 > 0 { *t = t.Add(time.Second) } n &= 0x3 if n == 0 { continue } if len(*b) < int(n) { return // invalid, not enough data } // add extra time data in 100's of nanoseconds d := time.Duration(0) for j := 3 - n; j < n; j++ { d |= time.Duration(b.byte()) << (j * 8) } d *= 100 *t = t.Add(d) } }
[ "func", "readExtTimes", "(", "f", "*", "fileBlockHeader", ",", "b", "*", "readBuf", ")", "{", "if", "len", "(", "*", "b", ")", "<", "2", "{", "return", "\n", "}", "\n", "flags", ":=", "b", ".", "uint16", "(", ")", "\n", "ts", ":=", "[", "]", "*", "time", ".", "Time", "{", "&", "f", ".", "ModificationTime", ",", "&", "f", ".", "CreationTime", ",", "&", "f", ".", "AccessTime", "}", "\n", "for", "i", ",", "t", ":=", "range", "ts", "{", "n", ":=", "flags", ">>", "uint", "(", "(", "3", "-", "i", ")", "*", "4", ")", "\n", "if", "n", "&", "0x8", "==", "0", "{", "continue", "\n", "}", "\n", "if", "i", "!=", "0", "{", "if", "len", "(", "*", "b", ")", "<", "4", "{", "return", "\n", "}", "\n", "*", "t", "=", "parseDosTime", "(", "b", ".", "uint32", "(", ")", ")", "\n", "}", "\n", "if", "n", "&", "0x4", ">", "0", "{", "*", "t", "=", "t", ".", "Add", "(", "time", ".", "Second", ")", "\n", "}", "\n", "n", "&=", "0x3", "\n", "if", "n", "==", "0", "{", "continue", "\n", "}", "\n", "if", "len", "(", "*", "b", ")", "<", "int", "(", "n", ")", "{", "return", "\n", "}", "\n", "d", ":=", "time", ".", "Duration", "(", "0", ")", "\n", "for", "j", ":=", "3", "-", "n", ";", "j", "<", "n", ";", "j", "++", "{", "d", "|=", "time", ".", "Duration", "(", "b", ".", "byte", "(", ")", ")", "<<", "(", "j", "*", "8", ")", "\n", "}", "\n", "d", "*=", "100", "\n", "*", "t", "=", "t", ".", "Add", "(", "d", ")", "\n", "}", "\n", "}" ]
// readExtTimes reads and parses the optional extra time field from the file header.
[ "readExtTimes", "reads", "and", "parses", "the", "optional", "extra", "time", "field", "from", "the", "file", "header", "." ]
197ef08ef68c4454ae5970a9c2692d6056ceb8d7
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive15.go#L196-L233
test