class Icalendar::Component

def ical_fold(long_line, indent = "\x20")

def ical_fold(long_line, indent = "\x20")
  # rfc2445 says:
  # Lines of text SHOULD NOT be longer than 75 octets, excluding the line
  # break. Long content lines SHOULD be split into a multiple line
  # representations using a line "folding" technique. That is, a long
  # line can be split between any two characters by inserting a CRLF
  # immediately followed by a single linear white space character (i.e.,
  # SPACE, US-ASCII decimal 32 or HTAB, US-ASCII decimal 9). Any sequence
  # of CRLF followed immediately by a single linear white space character
  # is ignored (i.e., removed) when processing the content type.
  #
  # Note the useage of "octets" and "characters": a line should not be longer
  # than 75 octets, but you need to split between characters, not bytes.
  # This is challanging with Unicode composing accents, for example.
  return long_line if long_line.bytesize <= Icalendar::MAX_LINE_LENGTH
  chars = long_line.scan(ICAL_FOLD_LONG_LINE_SCAN_REGEX) # split in graphenes
  folded = ['']
  bytes = 0
  while chars.count > 0
    c = chars.shift
    cb = c.bytes.count
    if bytes + cb > Icalendar::MAX_LINE_LENGTH
      # Split here
      folded.push "#{indent}"
      bytes = indent.bytes.count
    end
    folded[-1] += c
    bytes += cb
  end
  folded.join("\r\n")
end