Skip to content

Commit

Permalink
Added Vector class
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Sep 8, 2024
1 parent b2c6c0e commit b7914c3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 11 deletions.
15 changes: 4 additions & 11 deletions lib/pgvector.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import 'dart:convert';
import 'dart:typed_data';

import 'vector.dart';

class Pgvector {
const Pgvector();

// encode as text
String encode(List<double> input) {
return input.toString();
return Vector(input).toString();
}

// decode from binary
Expand All @@ -20,16 +22,7 @@ class Pgvector {
input = Uint8List.fromList(utf8.encode(input));
}
var bdata = new ByteData.view(input.buffer, input.offsetInBytes);
var dim = bdata.getUint16(0);
var unused = bdata.getUint16(2);
if (unused != 0) {
throw FormatException('expected unused to be 0');
}
var vec = <double>[];
for (var i = 0; i < dim; i++) {
vec.add(bdata.getFloat32(4 + i * 4));
}
return vec;
return Vector.fromBinary(bdata).toList();
}
}

Expand Down
29 changes: 29 additions & 0 deletions lib/vector.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import 'dart:typed_data';

class Vector {
final List<double> vec;

const Vector(this.vec);

factory Vector.fromBinary(ByteData bdata) {
var dim = bdata.getUint16(0);
var unused = bdata.getUint16(2);
if (unused != 0) {
throw FormatException('expected unused to be 0');
}
var vec = <double>[];
for (var i = 0; i < dim; i++) {
vec.add(bdata.getFloat32(4 + i * 4));
}
return Vector(vec);
}

List<double> toList() {
return vec;
}

@override
String toString() {
return vec.toString();
}
}

0 comments on commit b7914c3

Please sign in to comment.