What should I use to make a BTree persistent in Go?

blov · · 508 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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&#39;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>&#39;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&#39;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&#39;s a bit repetitive to make methods for all the types you want but certainly isn&#39;t too hard to do.</p> <p>Here&#39;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, &amp;i) return i } </code></pre> <p>using the imports: &#34;bytes&#34;, &#34;encoding/binary&#34;</p></pre>reven80: <pre><p>You can use gob if you don&#39;t care about the exact format of the encoding.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

508 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传