001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.reef.examples.group.utils.math; 020 021import org.apache.reef.wake.remote.Codec; 022 023import javax.inject.Inject; 024import java.io.*; 025 026/** 027 * Codec for the Vector type Uses Data*Stream. 028 */ 029public class VectorCodec implements Codec<Vector> { 030 /** 031 * This class is instantiated by TANG. 032 */ 033 @Inject 034 public VectorCodec() { 035 // Intentionally blank 036 } 037 038 @Override 039 public Vector decode(final byte[] data) { 040 final ByteArrayInputStream bais = new ByteArrayInputStream(data); 041 final Vector result; 042 try (DataInputStream dais = new DataInputStream(bais)) { 043 final int size = dais.readInt(); 044 result = new DenseVector(size); 045 for (int i = 0; i < size; i++) { 046 result.set(i, dais.readDouble()); 047 } 048 } catch (final IOException e) { 049 throw new RuntimeException(e); 050 } 051 return result; 052 } 053 054 @Override 055 public byte[] encode(final Vector vec) { 056 final ByteArrayOutputStream baos = new ByteArrayOutputStream(vec.size() 057 * (Double.SIZE / Byte.SIZE)); 058 try (DataOutputStream daos = new DataOutputStream(baos)) { 059 daos.writeInt(vec.size()); 060 for (int i = 0; i < vec.size(); i++) { 061 daos.writeDouble(vec.get(i)); 062 } 063 } catch (final IOException e) { 064 throw new RuntimeException(e); 065 } 066 return baos.toByteArray(); 067 } 068 069}