<p>So, I wrote this persistent BTree for my class in Java, following the CLRS algorithms.
We used <code>FileChannel</code> and <code>ByteBuffer</code> to store the tree in a file, reading and writing the nodes when needed.</p>
<p>I tried looking how I could make such a BTree in Go, and discovered <code>os.File</code>, which I think could be used the same way as Java's <code>FileChannel</code>.
However, I could not find an equivalent for <code>ByteBuffer</code>. I looked at <code>bytes.Buffer</code>, and I see how this could work, however it does not have the <code>ByteBuffer</code>'s handy <code>putInt</code>, <code>putDouble</code>, etc..</p>
<p>Would I have to implement myself those function to transform ints and doubles to byte arrays? I also looked at <code>encoding.binary</code>, but this looks very cumbersome. Basically having to encode the a byte array every time, then putting it in the buffer.</p>
<p>Does anyone have recommendations on structures to use?</p>
<hr/>**评论:**<br/><br/>TheMerovius: <pre><p>Basically… the same as in any other language. You can compose <a href="https://godoc.org/encoding/binary#Write" rel="nofollow">binary.Write</a> with <a href="https://godoc.org/bytes#Buffer" rel="nofollow">bytes.Buffer</a> for the simplest API, for example. Or you create your own struct type, wrapping bytes.Buffer and adding the methods you want (utilizing the more low-level API of <code>encoding/binary</code>), which shouldn't be more than a handful of LOC either.</p>
<p>The hard question is about deciding on an actual encoding, not how to code that up.</p></pre>PlainSight: <pre><p>It's a bit repetitive to make methods for all the types you want but certainly isn't too hard to do.</p>
<p>Here's an example of writing and reading int64 from a buffer</p>
<pre><code>func WriteInt64(buf *bytes.Buffer, i int64) {
binary.Write(buf, binary.LittleEndian, i)
}
func ReadInt64(buf *bytes.Buffer) int64 {
var i int64
binary.Read(buf, binary.LittleEndian, &i)
return i
}
</code></pre>
<p>using the imports: "bytes", "encoding/binary"</p></pre>reven80: <pre><p>You can use gob if you don't care about the exact format of the encoding.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传