小编Vla*_*eev的帖子

释放使用newCString分配的内存

正如库文档所说CString创建的newCString必须通过free函数释放.我一直在期待CString创建它时需要一些内存,当它被释放时free内存使用会下降,但它没有!这是示例代码:

module Main where

import Foreign
import Foreign.C.String
import System.IO

wait = do
  putStr "Press enter" >> hFlush stdout
  _ <- getLine
  return ()

main = do
  let s = concat $ replicate 1000000 ['0'..'9']
  cs <- newCString s
  cs `seq` wait   -- (1)

  free cs
  wait   -- (2)
Run Code Online (Sandbox Code Playgroud)

当程序停在(1)时,htop程序显示内存使用量大约为410M - 这没关系.我按回车键,程序在第(2)行停止,但内存使用率仍为410M,尽管cs已经是freed!

这怎么可能?用C编写的类似程序就像它应该的那样.我在这里错过了什么?

memory haskell memory-management ffi

10
推荐指数
1
解决办法
335
查看次数

即使使用NLL,循环中也会发生双重可变借用错误

假设我有几个结构,如下例所示,在next()方法中我需要使用用户提供的缓冲区来拉下一个事件,但是如果这个事件是注释,并且忽略comments标志设置为true,我需要拉下一个事件:

struct Parser {
    ignore_comments: bool,
}

enum XmlEvent<'buf> {
    Comment(&'buf str),
    Other(&'buf str),
}

impl Parser {
    fn next<'buf>(&mut self, buffer: &'buf mut String) -> XmlEvent<'buf> {
        let result = loop {
            buffer.clear();

            let temp_event = self.parse_outside_tag(buffer);

            match temp_event {
                XmlEvent::Comment(_) if self.ignore_comments => {}
                _ => break temp_event,
            }
        };
        result
    }

    fn parse_outside_tag<'buf>(&mut self, _buffer: &'buf mut String) -> XmlEvent<'buf> {
        unimplemented!()
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,即使#![feature(nll)]启用了以下代码,此代码也会出现双重借用错误:

error[E0499]: cannot borrow `*buffer` as mutable more than …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

9
推荐指数
2
解决办法
489
查看次数

异构地图

我需要一个可以包含任意值的映射,只要它们的类型具有相同的类型类.我的第一个天真的方法是这样的:

type HMap = forall a . MyClass a => M.Map Int a
Run Code Online (Sandbox Code Playgroud)

但它似乎不起作用:以下代码给出了编译错误:

testFunction :: (forall a . MyClass a => M.Map Int a) -> Int -> IO ()
testFunction m i = do
    case M.lookup i m of
        Nothing -> return ()
        Just v -> someActionFromMyClass v >> putStrLn "OK"


Ambiguous type variable `a0' in the constraint:
  (MyClass a0) arising from a use of `m'
Probable fix: add a type signature that fixes these type variable(s)
In the …
Run Code Online (Sandbox Code Playgroud)

polymorphism haskell existential-type higher-rank-types

8
推荐指数
1
解决办法
538
查看次数

Java 7 NIO.2 Files.getLastModifiedTime时区

我正在编写一个程序,需要确定上次修改时间的文件/目录.我想使用Joda Time处理这次,我正在使用Java 7 NIO.2类Files来获取文件的最后修改时间.它的getLastModifiedTime()方法返回一个FileTime类的实例,它有方便的方法toMillis(),其结果我传递给Joda Time DateTime类构造函数:

new DateTime(Files.getLastModifiedTime(path).toMillis());
Run Code Online (Sandbox Code Playgroud)

但是,我觉得我做错了,因为DateTime(long)构造函数明确提到DateTime将使用默认时区创建实例.FileTime但是,docs在任何地方都没有提到它的时区.我查看了FileTime代码; 它似乎非常简单,它的toString()方法表明它使用UTC时区(它Calendar在UTC时区创建一个并直接设置其毫秒).

那么,确实FileTime使用UTC或当地时间吗?什么是转换正确的方式FileTimeDateTime

java datetime date jodatime nio2

8
推荐指数
1
解决办法
5178
查看次数

将元素从外部推送到 fs2 中的反应流

我有一个外部(即,我无法更改它)Java API,如下所示:

public interface Sender {
    void send(Event e);
}
Run Code Online (Sandbox Code Playgroud)

我需要实现一个Sender接受每个事件,将其转换为 JSON 对象,将其中一些收集到一个包中并通过 HTTP 发送到某个端点的。这一切都应该异步完成,没有send()阻塞调用线程,使用一些固定大小的缓冲区并在缓冲区已满时丢弃新事件。

使用 akka-streams 这很简单:我创建了一个阶段图(它使用 akka-http 发送 HTTP 请求),将它具体化并使用具体化ActorRef将新事件推送到流:

lazy val eventPipeline = Source.actorRef[Event](Int.MaxValue, OverflowStrategy.fail)
  .via(CustomBuffer(bufferSize))  // buffer all events
  .groupedWithin(batchSize, flushDuration)  // group events into chunks
  .map(toBundle)  // convert each chunk into a JSON message
  .mapAsyncUnordered(1)(sendHttpRequest)  // send an HTTP request
  .toMat(Sink.foreach { response =>
    // print HTTP response for debugging
  })(Keep.both)

lazy val (eventsActor, completeFuture) = eventPipeline.run()

override def …
Run Code Online (Sandbox Code Playgroud)

scala reactive-streams akka-stream fs2

8
推荐指数
1
解决办法
953
查看次数

Maven pluginManagement配置继承奇怪的行为

pluginManagement在我的父母中使用元素pom.xml为其所有子节点配置插件.例如,我有以下配置:

<pluginManagement>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.4.3</version>
        <executions>
            <execution>
                <id>copy-artifacts</id>
                <phase>install</phase>
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <outputDirectory>some/where/else</outputDirectory>
                    <resources>
                        <resource>
                            <directory>some/another/resource</directory>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.4</version>
        <executions>
            <execution>
                <id>copy-dependencies</id>
                <phase>install</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                    <outputDirectory>deps/dir</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>
</pluginManagement>
Run Code Online (Sandbox Code Playgroud)

官方文档指出pluginManagement仍然必须将配置的插件添加到plugins子poms中的元素中.事实上,如果我从孩子pom中删除它:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
</plugin>
Run Code Online (Sandbox Code Playgroud)

然后maven-dependency-plugininstall阶段停止射击.但是,似乎它不会影响其他一些插件,即maven-resource-plugin.即使我没有

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
</plugin>
Run Code Online (Sandbox Code Playgroud)

在我的孩子pom中,它的copy-resources目标仍然在install阶段激发并执行它配置的工作.

为什么会出现这种行为?是否有一个总是继承的插件列表,或者我可能遗漏了什么?

inheritance build maven-plugin pom.xml maven

7
推荐指数
1
解决办法
5386
查看次数

使用默认参数验证模拟对象方法调用

假设我有这个课程:

class Defaults {
  def doSomething(regular: String, default: Option[String] = None) = {
    println(s"Doing something: $regular, $default")
  }
}
Run Code Online (Sandbox Code Playgroud)

我想检查一些其他类doSomething()Defaults实例上调用方法而不传递第二个参数:

defaults.doSomething("abcd")  // second argument is None implicitly
Run Code Online (Sandbox Code Playgroud)

但是,模拟Defaults类无法正常工作.因为方法参数的默认值在同一个类中被编译为隐藏方法,所以mock[Defaults]返回一个对象,其中这些隐藏方法返回null而不是None,因此此测试失败:

class Test extends FreeSpec with ShouldMatchers with MockitoSugar {
  "Defaults" - {
    "should be called with default argument" in {
      val d = mock[Defaults]

      d.doSomething("abcd")

      verify(d).doSomething("abcd", None)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

错误:

Argument(s) are different! Wanted:
defaults.doSomething("abcd", None);
-> at defaults.Test$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(Test.scala:14) …
Run Code Online (Sandbox Code Playgroud)

scala mockito default-arguments

7
推荐指数
1
解决办法
1946
查看次数

如何从输出的同一行读取键盘上的字符串?

我正在读这样的字符串:

print!("Input string: "); 

let string: String = String::new();
std::io::stdin().read_line(&mut string);
Run Code Online (Sandbox Code Playgroud)

当我启动程序时,我看到:

(write a string here)
Input string:
Run Code Online (Sandbox Code Playgroud)

但是我需要:

Input string: (write a string here)
Run Code Online (Sandbox Code Playgroud)

怎么实现这个?

string io rust

7
推荐指数
1
解决办法
753
查看次数

宏中的令牌树(处理参数列表)

目前,将扩展方法添加到另一个模块中的类型(即使该模块在子模块中)的唯一方法是定义一个新特征并为该类型实现它。然而,这非常笨拙,因为方法的数量变得很大:

trait Ops {
    fn parse_list_item(&self, current_item: ListItemInfo) 
        -> ParseResult<(Document, ListItemInfo)>;
    fn parse_list_item_content(&self) -> ParseResult<Document>;
}

impl<'a> Ops for MarkdownParser<'a> {
    fn parse_list_item(&self, current_item: ListItemInfo) 
            -> ParseResult<(Document, ListItemInfo)> {
        // ...
    }

    fn parse_list_item_content(&self) -> ParseResult<Document> {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

你必须写两次方法签名。如果它发生变化,您还必须在多个地方更新它。它还增加了很多噪音。

我认为宏会有所帮助,但我不知道如何macro_rules!为函数中的参数列表编写正确的模式。这是我到目前为止所拥有的:

#![feature(macro_rules)]

struct Foo;

macro_rules! ops (
    ($(fn $name:ident($($args:tt)*) -> $ret:ty $body:block)+) => (
        trait Ops {
            $(fn $name($($args)*) -> $ret;)+
        }

        impl Ops for Foo {
            $(fn $name($($args)*) -> $ret $body)+
        }
    )
)

mod …
Run Code Online (Sandbox Code Playgroud)

macros rust

6
推荐指数
0
解决办法
1231
查看次数

存在型包装必需品

事实证明,尽管背后有非常简单的想法,但正确地使用存在/秩n类型却非常困难.

为什么需要将存在类型包装到data类型中?

我有以下简单示例:

{-# LANGUAGE RankNTypes, ImpredicativeTypes, ExistentialQuantification #-}
module Main where

c :: Double
c = 3

-- Moving `forall` clause from here to the front of the type tuple does not help,
-- error is the same
lists :: [(Int, forall a. Show a => Int -> a)]
lists = [ (1, \x -> x)
        , (2, \x -> show x)
        , (3, \x -> c^x)
        ]

data HRF = forall a. Show a => HRF …
Run Code Online (Sandbox Code Playgroud)

polymorphism haskell existential-type higher-rank-types

5
推荐指数
2
解决办法
368
查看次数