code: def rewrite_text_stream_to_gen(self, stream, rwinfo):
          
          try:
              buff = self.first_buff
  
              # for html rewriting:
              # if charset is utf-8, use that, otherwise default to encode to ascii-compatible encoding
              # encoding only used for url rewriting, encoding back to bytes after rewriting
              if rwinfo.charset == 'utf-8' and rwinfo.text_type == 'html':
                  charset = 'utf-8'
              else:
                  charset = 'iso-8859-1'
  
              if buff:
                  yield buff.encode(charset)
  
              decoder = codecs.getincrementaldecoder(charset)()
  
              while True:
                  buff = stream.read(BUFF_SIZE)
                  if not buff:
                      break
  
                  if self.align_to_line:
                      buff += stream.readline()
  
                  try:
                      buff = decoder.decode(buff)
                  except UnicodeDecodeError:
                      if charset == 'utf-8':
                          rwinfo.charset = 'iso-8859-1'
                          charset = rwinfo.charset
                          decoder = codecs.getincrementaldecoder(charset)()
                          buff = decoder.decode(buff)
  
                  buff = self.rewrite(buff)
  
                  yield buff.encode(charset)
  
              # For adding a tail/handling final buffer
              buff = self.final_read()
  
              # ensure decoder is marked as finished (final buffer already decoded)
              decoder.decode(b'', final=True)
  
              if buff:
                  yield buff.encode(charset)
  
          finally:
              stream.close()
docs: Convert stream to generator using applying rewriting func
          to each portion of the stream.
          Align to line boundaries if needed.