github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/compression/snappy/snappy.go (about) 1 // Copyright 2020 DataStax 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package snappy 16 17 import ( 18 "bytes" 19 "fmt" 20 "io" 21 22 "github.com/golang/snappy" 23 ) 24 25 // Compressor satisfies frame.BodyCompressor for the SNAPPY algorithm. 26 type Compressor struct{} 27 28 func (l Compressor) CompressWithLength(source io.Reader, dest io.Writer) error { 29 if uncompressedMessage, err := bufferFromReader(source); err != nil { 30 return fmt.Errorf("cannot read uncompressed message: %w", err) 31 } else { 32 compressedMessage := snappy.Encode(nil, uncompressedMessage.Bytes()) 33 if _, err := dest.Write(compressedMessage); err != nil { 34 return fmt.Errorf("cannot write compressed message: %w", err) 35 } 36 return nil 37 } 38 } 39 40 func (l Compressor) DecompressWithLength(source io.Reader, dest io.Writer) error { 41 if compressedMessage, err := bufferFromReader(source); err != nil { 42 return fmt.Errorf("cannot read compressed message: %w", err) 43 } else { 44 if decompressedMessage, err := snappy.Decode(nil, compressedMessage.Bytes()); err != nil { 45 return fmt.Errorf("cannot decompress message: %w", err) 46 } else if _, err := dest.Write(decompressedMessage); err != nil { 47 return fmt.Errorf("cannot write decompressed message: %w", err) 48 } 49 return nil 50 } 51 } 52 53 func bufferFromReader(source io.Reader) (*bytes.Buffer, error) { 54 var buf *bytes.Buffer 55 switch s := source.(type) { 56 case *bytes.Buffer: 57 buf = s 58 default: 59 buf = &bytes.Buffer{} 60 if _, err := buf.ReadFrom(s); err != nil { 61 return nil, err 62 } 63 } 64 return buf, nil 65 }