arrow/util/string_writer.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! String Writer
6//! This string writer encapsulates `std::string::String` and
7//! implements `std::io::Write` trait, which makes String as a
8//! writable object like File.
9//!
10//! Example:
11//!
12//! ```
13//! #[cfg(feature = "csv")]
14//! {
15//! use arrow::array::*;
16//! use arrow::csv;
17//! use arrow::datatypes::*;
18//! use arrow::record_batch::RecordBatch;
19//! use arrow::util::string_writer::StringWriter;
20//! use std::sync::Arc;
21//!
22//! let schema = Schema::new(vec![
23//! Field::new("c1", DataType::Utf8, false),
24//! Field::new("c2", DataType::Float64, true),
25//! Field::new("c3", DataType::UInt32, false),
26//! Field::new("c3", DataType::Boolean, true),
27//! ]);
28//! let c1 = StringArray::from(vec![
29//! "Lorem ipsum dolor sit amet",
30//! "consectetur adipiscing elit",
31//! "sed do eiusmod tempor",
32//! ]);
33//! let c2 = PrimitiveArray::<Float64Type>::from(vec![
34//! Some(123.564532),
35//! None,
36//! Some(-556132.25),
37//! ]);
38//! let c3 = PrimitiveArray::<UInt32Type>::from(vec![3, 2, 1]);
39//! let c4 = BooleanArray::from(vec![Some(true), Some(false), None]);
40//!
41//! let batch = RecordBatch::try_new(
42//! Arc::new(schema),
43//! vec![Arc::new(c1), Arc::new(c2), Arc::new(c3), Arc::new(c4)],
44//! )
45//! .unwrap();
46//!
47//! let sw = StringWriter::new();
48//! let mut writer = csv::Writer::new(sw);
49//! writer.write(&batch).unwrap();
50//! }
51//! ```
52
53use core::str;
54use std::fmt::Formatter;
55use std::io::{Error, ErrorKind, Result, Write};
56
57/// A writer that allows writing to a `String`
58/// like an `std::io::Write` object.
59#[derive(Debug, Default)]
60pub struct StringWriter {
61 data: String,
62}
63
64impl StringWriter {
65 /// Create a new `StringWriter`
66 pub fn new() -> Self {
67 Self::default()
68 }
69}
70
71impl std::fmt::Display for StringWriter {
72 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
73 write!(f, "{}", self.data)
74 }
75}
76
77impl Write for StringWriter {
78 fn write(&mut self, buf: &[u8]) -> Result<usize> {
79 let string = match str::from_utf8(buf) {
80 Ok(x) => x,
81 Err(e) => {
82 return Err(Error::new(ErrorKind::InvalidData, e));
83 }
84 };
85 self.data.push_str(string);
86 Ok(string.len())
87 }
88
89 fn flush(&mut self) -> Result<()> {
90 Ok(())
91 }
92}