Module: Virginity::LineFolding

Defined in:
lib/virginity/dir_info/line_folding.rb

Constant Summary collapse

LINE_ENDING =

the order is important!

/\r\n|\n|\r/
FOLD =

we accept unix-newlines and mac-newlines too (spec says only windows newlines, rn, are okay)

/(#{LINE_ENDING})[\t\ ]/

Class Method Summary collapse

Class Method Details

.fold(card) ⇒ Object

This is way faster than the method above and unicode-safe it is slightly different: it does not count bytes, it counts characters



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/virginity/dir_info/line_folding.rb', line 30

def self.fold(card, width = 75)
  return card unless width > 0
  # binary fields should already be encoded to a width that is smaller than width
  scanner = StringScanner.new(card)
  folded = ""
  line_pos = 0
  while !scanner.eos?
    char = scanner.getch
    charsize = char.size
    if line_pos + charsize > width
      folded << "\n "
      line_pos = 0
    end
    folded << char
    char == "\n" ? line_pos = 0 : line_pos += charsize
  end
  folded
end

.fold_ascii(card, width = 75) ⇒ Object

TODO: option to encode with “rn” instead of “n”? not multibyte-safe but very safe for ascii



22
23
24
25
26
# File 'lib/virginity/dir_info/line_folding.rb', line 22

def self.fold_ascii(card, width = 75)
  return card unless width > 0
  # binary should already be encoded to a width that is smaller than width
  card.gsub(/.{#{width}}/, "\\0\n ") # "\\0" is the matched string
end

.unfold(card) ⇒ Object

5.8.1. Line delimiting and folding. A logical line MAY be continued on the next physical line anywhere between two characters by inserting a CRLF immediately followed by a single white space character (space, ASCII decimal 32, or horizontal tab, ASCII decimal 9). At least one character must be present on the folded line. Any sequence of CRLF followed immediately by a single white space character is ignored (removed) when processing the content type.



12
13
14
# File 'lib/virginity/dir_info/line_folding.rb', line 12

def self.unfold(card)
  card.gsub(FOLD, '')
end

.unfold_and_split(string) ⇒ Object



16
17
18
# File 'lib/virginity/dir_info/line_folding.rb', line 16

def self.unfold_and_split(string)
  unfold(string).split(LINE_ENDING)
end