예제 #1
0
파일: writer.go 프로젝트: shuLhan/dsv
//
// WriteRawColumns write raw columns using separator `sep` for each record to
// file.
//
// We use pointer in separator parameter, so we can use empty string as
// separator.
//
func (writer *Writer) WriteRawColumns(cols *tabula.Columns, sep *string) (
	nrow int,
	e error,
) {
	ncol := len(*cols)
	if ncol <= 0 {
		return
	}

	if sep == nil {
		sep = new(string)
		*sep = DefSeparator
	}

	// Find minimum and maximum column length.
	minlen, maxlen := cols.GetMinMaxLength()

	esc := []byte(DefEscape)
	sepbytes := []byte(*sep)
	x := 0

	// First, write until minimum column length.
	for ; x < minlen; x++ {
		v := cols.Join(x, sepbytes, esc)
		v = append(v, DefEOL)

		_, e = writer.BufWriter.Write(v)

		if nil != e {
			return x, e
		}
	}

	// and then write column until max length.
	for ; x < maxlen; x++ {
		v := cols.Join(x, sepbytes, esc)
		v = append(v, DefEOL)

		_, e = writer.BufWriter.Write(v)

		if nil != e {
			break
		}
	}

	_ = writer.Flush()
	return x, e
}
예제 #2
0
파일: writer.go 프로젝트: shuLhan/dsv
/*
WriteColumns will write content of columns to output file.
Return n for number of row written, and e if error happened.
*/
func (writer *Writer) WriteColumns(columns tabula.Columns,
	colMd []MetadataInterface,
) (
	n int,
	e error,
) {
	nColumns := len(columns)
	if nColumns <= 0 {
		return
	}

	emptyRec := tabula.NewRecordString("")

	// Get minimum and maximum length of all columns.
	// In case one of the column have different length (shorter or longer),
	// we will take the column with minimum length first and continue with
	// the maximum length.

	minlen, maxlen := columns.GetMinMaxLength()

	// If metadata is nil, generate it from column name.
	if colMd == nil {
		for _, col := range columns {
			md := &Metadata{
				Name: col.Name,
				T:    col.Type,
			}

			colMd = append(colMd, md)
		}
	}

	// First loop, iterate until minimum column length.
	row := make(tabula.Row, nColumns)

	for ; n < minlen; n++ {
		// Convert columns to record.
		for y, col := range columns {
			row[y] = col.Records[n]
		}

		e = writer.WriteRow(&row, colMd)
		if e != nil {
			goto err
		}
	}

	// Second loop, iterate until maximum column length.
	for ; n < maxlen; n++ {
		// Convert columns to record.
		for y, col := range columns {
			if col.Len() > n {
				row[y] = col.Records[n]
			} else {
				row[y] = emptyRec
			}
		}

		e = writer.WriteRow(&row, colMd)
		if e != nil {
			goto err
		}
	}

err:
	_ = writer.Flush()
	return n, e
}