]> ruderich.org/simon Gitweb - safcm/safcm.git/blobdiff - gob.go
First working version
[safcm/safcm.git] / gob.go
diff --git a/gob.go b/gob.go
new file mode 100644 (file)
index 0000000..147ea23
--- /dev/null
+++ b/gob.go
@@ -0,0 +1,50 @@
+// RPC primitives for safcm: basic connection implementation
+
+// Copyright (C) 2021  Simon Ruderich
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+package safcm
+
+import (
+       "encoding/gob"
+       "io"
+)
+
+type GobConn struct {
+       enc *gob.Encoder
+       dec *gob.Decoder
+}
+
+func NewGobConn(r io.Reader, w io.Writer) *GobConn {
+       return &GobConn{
+               enc: gob.NewEncoder(w),
+               dec: gob.NewDecoder(r),
+       }
+}
+
+func (c *GobConn) Send(x Msg) error {
+       // & lets Encode send the interface itself and not a concrete type
+       // which is necessary to Decode as an interface
+       return c.enc.Encode(&x)
+}
+
+func (c *GobConn) Recv() (Msg, error) {
+       var x Msg
+       err := c.dec.Decode(&x)
+       if err != nil {
+               return nil, err
+       }
+       return x, nil
+}