View Javadoc
1   /*
2    * Copyright 2008, 2009 Ange Optimization ApS
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package eu.simuline.octave.io.impl;
17  
18  import java.io.IOException;
19  import java.io.Writer;
20  import java.util.Map;
21  
22  import eu.simuline.octave.io.OctaveIO;
23  import eu.simuline.octave.io.spi.OctaveDataWriter;
24  import eu.simuline.octave.type.OctaveObject;
25  import eu.simuline.octave.type.OctaveStruct;
26  
27  // import static eu.simuline.octave.io.impl.CellWriter.NROWS;
28  // import static eu.simuline.octave.io.impl.CellWriter.NCOLUMNS;
29  
30  /**
31   * The writer for the octave type "struct" 
32   * writing an {@link OctaveStruct} to a {@link Writer}. 
33   *
34   * The format is 
35   * <pre>
36   * # type: struct\n
37   * # length: ...\n
38   * // comment: the following is in a loop of given length 
39   * </pre>
40   */
41  public final class StructWriter extends OctaveDataWriter<OctaveStruct> {
42      static final String LENGTH = "# length: ";
43      static final String NAME   = "# name: ";
44  
45      static final String TYPE_CELL = "# type: cell";
46  
47      @Override
48      public Class<OctaveStruct> javaType() {
49          return OctaveStruct.class;
50      }
51  
52      @Override
53      public void write(final Writer writer,
54  		      final OctaveStruct octaveStruct) throws IOException {
55          writer.write("# type: struct\n");
56          final Map<String, OctaveObject> data = octaveStruct.getData();
57          writer.write(LENGTH + data.size() + "\n");
58          for (final Map.Entry<String, OctaveObject> entry : data.entrySet()) {
59              final String subname = entry.getKey();
60              final OctaveObject value = entry.getValue();
61              writer.write(NAME + subname + "\n");
62  
63  	    // **** what follows seems to correspond with CellReader 
64              writer.write(TYPE_CELL + "\n");
65  //            writer.write("# type: cell\n");
66              writer.write("# rows: " + 1 + "\n");
67              writer.write("# columns: " + 1 + "\n");
68              OctaveIO.write(writer, "<cell-element>", value);
69              writer.write("\n");
70          }
71      }
72  
73  }